Python libvirt.VIR_DOMAIN_AFFECT_LIVE Examples

The following are 22 code examples of libvirt.VIR_DOMAIN_AFFECT_LIVE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module libvirt , or try the search function .
Example #1
Source File: disk_drive.py    From MCVirt with GNU General Public License v2.0 6 votes vote down vote up
def attach_iso(self, iso_object, live=False):
        """Attaches an ISO image to the disk drive of the VM."""
        iso_object = self.po__convert_remote_object(iso_object)

        # Ensure that the user has permissions to modifiy the VM
        self.po__get_registered_object('auth').assert_permission(
            PERMISSIONS.MODIFY_VM,
            self.vm_object
        )

        # Import cdrom XML template
        cdrom_xml = ET.parse(DirectoryLocation.TEMPLATE_DIR + '/cdrom.xml')

        # Add iso image path to cdrom XML
        cdrom_xml.find('source').set('file', iso_object.get_path())
        cdrom_xml_string = ET.tostring(cdrom_xml.getroot(), encoding='utf8', method='xml')

        flags = libvirt.VIR_DOMAIN_AFFECT_LIVE if live else 0

        # Update the libvirt cdrom device
        libvirt_object = self.vm_object._get_libvirt_domain_object()
        if libvirt_object.updateDeviceFlags(cdrom_xml_string, flags):
            raise LibvirtException('An error occurred whilst attaching ISO') 
Example #2
Source File: disk_drive.py    From MCVirt with GNU General Public License v2.0 6 votes vote down vote up
def remove_iso(self, live=False):
        """Removes ISO attached to the disk drive of a VM."""

        # Import cdrom XML template
        cdrom_xml = ET.parse(DirectoryLocation.TEMPLATE_DIR + '/cdrom.xml')

        # Add iso image path to cdrom XML
        cdrom_xml = cdrom_xml.getroot()
        source_xml = cdrom_xml.find('source')

        if source_xml is not None:
            cdrom_xml.remove(source_xml)
            cdrom_xml_string = ET.tostring(cdrom_xml, encoding='utf8', method='xml')
            flags = libvirt.VIR_DOMAIN_AFFECT_LIVE if live else 0

            # Update the libvirt cdrom device
            if self.vm_object._get_libvirt_domain_object().updateDeviceFlags(
                    cdrom_xml_string, flags):
                raise LibvirtException('An error occurred whilst detaching ISO') 
Example #3
Source File: __init__.py    From kcli with Apache License 2.0 6 votes vote down vote up
def update_memory(self, name, memory):
        conn = self.conn
        memory = str(int(memory) * 1024)
        try:
            vm = conn.lookupByName(name)
        except:
            print("VM %s not found" % name)
            return {'result': 'failure', 'reason': "VM %s not found" % name}
        xml = vm.XMLDesc(0)
        root = ET.fromstring(xml)
        memorynode = list(root.getiterator('memory'))[0]
        memorynode.text = memory
        currentmemory = list(root.getiterator('currentMemory'))[0]
        maxmemory = list(root.getiterator('maxMemory'))
        if maxmemory:
            diff = int(memory) - int(currentmemory.text)
            if diff > 0:
                xml = "<memory model='dimm'><target><size unit='KiB'>%s</size><node>0</node></target></memory>" % diff
                vm.attachDeviceFlags(xml, VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)
        elif vm.isActive():
            common.pprint("Note this will only be effective upon next start", color='blue')
        currentmemory.text = memory
        newxml = ET.tostring(root)
        conn.defineXML(newxml.decode("utf-8"))
        return {'result': 'success'} 
Example #4
Source File: vmtest_helper.py    From nitro with GNU General Public License v3.0 5 votes vote down vote up
def mount_cdrom(self, cdrom_path):
        logging.info('Mounting CDROM image')
        dom_elem = tree.fromstring(self.domain.XMLDesc())
        # find cdrom
        cdrom_elem = dom_elem.find("./devices/disk[@device='cdrom']")
        # find source
        source_elem = cdrom_elem.find('./source')
        if source_elem is None:
            tree.SubElement(cdrom_elem, 'source')
            source_elem = cdrom_elem.find('./source')
        source_elem.set('file', cdrom_path)
        new_xml = tree.tostring(cdrom_elem).decode('utf-8')
        result = self.domain.updateDeviceFlags(new_xml, libvirt.VIR_DOMAIN_AFFECT_LIVE)
        logging.debug("updateDeviceFlags returned %s", result) 
Example #5
Source File: del_iothread.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def del_iothread(params):
    """
       test API for delIOThread in class virDomain
    """

    logger = params['logger']
    id = int(params['id'])

    try:
        conn = libvirt.open(params['conn'])

        logger.info("get connection to libvirtd")
        guest = params['guestname']
        vm = conn.lookupByName(guest)
        logger.info("test guest name: %s" % guest)

        """ test effect guest running XML """
        if vm.isActive() == 1:
            logger.info("guest is running test with running guest")
            if find_iothreadid_fromxml(vm, 1, id):
                vm.delIOThread(id, libvirt.VIR_DOMAIN_AFFECT_LIVE)
                if find_iothreadid_fromxml(vm, 1, id):
                    logger.info("FAIL: still can find iothread id in XML")
                    return 1
        else:
            """ test effect guest config"""
            logger.info("test with guest inactive XML")
            if find_iothreadid_fromxml(vm, 0, id):
                vm.delIOThread(id, libvirt.VIR_DOMAIN_AFFECT_CONFIG)
                if find_iothreadid_fromxml(vm, 0, id):
                    logger.info("FAIL: still can find iothread id in XML")
                    return 1

        logger.info("PASS: delete iothread successful.")
    except libvirtError as e:
        logger.error("API error message: %s" % e.get_error_message())
        return 1
    return 0 
Example #6
Source File: set_metadata_type.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def parse_flag(logger, params):
    flag = params.get('flags', 'current')
    ret = 0
    logger.info("setMetadata with flag %s" % flag)
    if flag == 'current':
        return libvirt.VIR_DOMAIN_AFFECT_CURRENT
    for flag in flag.split('|'):
        if flag == 'live':
            ret = ret | libvirt.VIR_DOMAIN_AFFECT_LIVE
        elif flag == 'config':
            ret = ret | libvirt.VIR_DOMAIN_AFFECT_CONFIG
        else:
            logger.error('illegal flag %s' % flag)
            return -1
    return ret 
Example #7
Source File: set_metadata.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def parse_flag(logger, params):
    flag = params.get('flags', 'current')
    ret = 0
    logger.info("setMetadata with flag %s" % flag)
    if flag == 'current':
        return libvirt.VIR_DOMAIN_AFFECT_CURRENT
    for flag in flag.split('|'):
        if flag == 'live':
            ret = ret | libvirt.VIR_DOMAIN_AFFECT_LIVE
        elif flag == 'config':
            ret = ret | libvirt.VIR_DOMAIN_AFFECT_CONFIG
        else:
            logger.error('illegal flag %s' % flag)
            return -1
    return ret 
Example #8
Source File: perf_events.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def parse_flag(params, logger):
    flags = params.get('flags', 'current')
    logger.info("Flag: %s" % flags)
    if flags == "current":
        return libvirt.VIR_DOMAIN_AFFECT_CURRENT
    elif flags == "live":
        return libvirt.VIR_DOMAIN_AFFECT_LIVE
    elif flags == "config":
        return libvirt.VIR_DOMAIN_AFFECT_CONFIG
    else:
        logger.error("Not support flag: %s" % flags)
        return -1 
Example #9
Source File: set_perf_events.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def check_events(events, event_list, guestname, flags, domstate, dom, logger):
    values = {}
    if ((domstate == libvirt.VIR_DOMAIN_RUNNING) and
        ((flags == libvirt.VIR_DOMAIN_AFFECT_CURRENT) or
         (flags == libvirt.VIR_DOMAIN_AFFECT_LIVE))):
        xmlstr = minidom.parse("%s%s.xml" % (XML_PATH, guestname))
    else:
        guestxml = dom.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
        xmlstr = minidom.parseString(guestxml)

    perf = xmlstr.getElementsByTagName('perf')
    if perf:
        perf = xmlstr.getElementsByTagName('perf')[0]
        for item in perf.getElementsByTagName('event'):
            for i in event_list:
                if item.getAttribute('name') == i:
                    if item.getAttribute('enabled') == "yes":
                        values[i] = True
                    elif item.getAttribute('enabled') == "no":
                        values[i] = False

    logger.info("values: %s" % values)
    for i in event_list:
        if i in list(values.keys()) and i in list(events.keys()):
            if values[i] != events[i]:
                return 1

    return 0 
Example #10
Source File: get_metadata.py    From libvirt-test-API with GNU General Public License v2.0 5 votes vote down vote up
def parse_flag(logger, params):
    flag = params.get('flags', 'current')
    ret = 0
    logger.info("metadata with flag %s" % flag)
    if flag == 'current':
        return libvirt.VIR_DOMAIN_AFFECT_CURRENT
    for flag in flag.split('|'):
        if flag == 'live':
            ret = ret | libvirt.VIR_DOMAIN_AFFECT_LIVE
        elif flag == 'config':
            ret = ret | libvirt.VIR_DOMAIN_AFFECT_CONFIG
        else:
            logger.error('illegal flag %s' % flag)
            return -1
    return ret 
Example #11
Source File: __init__.py    From kcli with Apache License 2.0 5 votes vote down vote up
def add_nic(self, name, network):
        conn = self.conn
        networks = {}
        for interface in conn.listInterfaces():
            networks[interface] = 'bridge'
        for net in conn.listAllNetworks():
            networks[net.name()] = 'network'
        try:
            vm = conn.lookupByName(name)
        except:
            common.pprint("VM %s not found" % name, color='red')
            return {'result': 'failure', 'reason': "VM %s not found" % name}
        if network not in networks:
            common.pprint("Network %s not found" % network, color='red')
            return {'result': 'failure', 'reason': "Network %s not found" % network}
        else:
            networktype = networks[network]
            source = "<source %s='%s'/>" % (networktype, network)
        nicxml = """<interface type='%s'>
                    %s
                    <model type='virtio'/>
                    </interface>""" % (networktype, source)
        if vm.isActive() == 1:
            vm.attachDeviceFlags(nicxml, VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)
        else:
            vm.attachDeviceFlags(nicxml, VIR_DOMAIN_AFFECT_CONFIG)
        vm = conn.lookupByName(name)
        vmxml = vm.XMLDesc(0)
        conn.defineXML(vmxml)
        return {'result': 'success'} 
Example #12
Source File: usb_device.py    From MCVirt with GNU General Public License v2.0 5 votes vote down vote up
def detach(self):
        """Detach the USB device from the libvirt domain."""
        if not self.virtual_machine.is_running:
            raise VmStoppedException('VM is stopped. '
                                     'Can only attached USB device to running VM')

        # TO ADD PERMISSION CHECKING
        libvirt_object = self.virtual_machine._get_libvirt_domain_object()
        libvirt_object.detachDeviceFlags(
            self._generate_libvirt_xml(),
            (libvirt.VIR_DOMAIN_AFFECT_LIVE |
             libvirt.VIR_DOMAIN_AFFECT_CURRENT |
             libvirt.VIR_DOMAIN_AFFECT_CONFIG)) 
Example #13
Source File: usb_device.py    From MCVirt with GNU General Public License v2.0 5 votes vote down vote up
def attach(self):
        """Attach the USB device to the libvirt domain."""
        if not self.virtual_machine.is_running:
            raise VmStoppedException('VM is stopped. '
                                     'Can only attached USB device to running VM')
        # TO ADD PERMISSION CHECKING
        libvirt_object = self.virtual_machine._get_libvirt_domain_object()
        libvirt_object.attachDeviceFlags(
            self._generate_libvirt_xml(),
            (libvirt.VIR_DOMAIN_AFFECT_LIVE |
             libvirt.VIR_DOMAIN_AFFECT_CURRENT |
             libvirt.VIR_DOMAIN_AFFECT_CONFIG)) 
Example #14
Source File: vcpupin_live.py    From libvirt-test-API with GNU General Public License v2.0 4 votes vote down vote up
def vcpupin_live(params):
    """pin domain vcpu to host cpu with live flag
    """
    global logger
    logger = params['logger']
    params.pop('logger')
    guestname = params['guestname']
    vcpu = int(params['vcpu'])
    cpulist = params['cpulist']

    logger.info("the name of virtual machine is %s" % guestname)
    logger.info("the given vcpu is %s" % vcpu)
    logger.info("the given cpulist is %s" % cpulist)

    global maxcpu
    conn = sharedmod.libvirtobj['conn']
    if utils.isPower():
        maxcpu = conn.getMaxVcpus('kvm')
    else:
        maxcpu = utils.get_host_cpus()
    logger.info("%s physical cpu on host" % maxcpu)

    try:
        domobj = conn.lookupByName(guestname)
        cpumap = utils.param_to_tuple(cpulist, maxcpu)
        if not cpumap:
            logger.error("cpulist: Invalid format")
            return 1

        logger.debug("cpumap for vcpu pin is:")
        logger.debug(cpumap)

        logger.info("pin domain vcpu %s to host cpu %s with flag: %s" %
                    (vcpu, cpulist, libvirt.VIR_DOMAIN_AFFECT_LIVE))
        domobj.pinVcpuFlags(vcpu, cpumap, libvirt.VIR_DOMAIN_AFFECT_LIVE)

        logger.info("check vcpus info")
        ret = domobj.vcpus()
        logger.debug("vcpus info is:")
        logger.debug(ret)
        if ret[1][vcpu] == cpumap:
            logger.info("vcpus info is expected")
        else:
            logger.error("vcpus info is not expected")
            return 1

    except libvirtError as e:
        logger.error("libvirt call failed: " + str(e))
        return 1

    logger.info("check vcpu pin status on host")
    ret = vcpupin_check(guestname, vcpu, cpulist)
    if ret:
        logger.error("domain vcpu pin failed")
        return 1
    else:
        logger.info("domain vcpu pin succeed")
        return 0 
Example #15
Source File: add_iothread.py    From libvirt-test-API with GNU General Public License v2.0 4 votes vote down vote up
def add_iothread(params):
    """
       test API for addIOThread in class virDomain
    """

    logger = params['logger']
    id = int(params['id'])

    if utils.check_qemu_package("qemu-kvm") and not utils.version_compare("qemu-kvm", 2, 12, 0, logger):
        logger.info("Current qemu-kvm don't support this API.")
        return 0

    try:
        conn = libvirt.open(params['conn'])

        logger.info("get connection to libvirtd")
        guest = params['guestname']
        vm = conn.lookupByName(guest)
        logger.info("test guest name: %s" % guest)

        """ test effect guest running XML """
        if vm.isActive() == 1:
            logger.info("guest is running test with running guest")
            if not find_iothreadid_fromxml(vm, 1, id):
                logger.info("add iothread %d to running guest" % id)
                vm.addIOThread(id, libvirt.VIR_DOMAIN_AFFECT_LIVE)
                if not find_iothreadid_fromxml(vm, 1, id):
                    logger.info("FAIL: cannot find iothread id in XML")
                    return 1
        else:
            """ test effect guest config"""
            logger.info("test with guest inactive XML")
            if not find_iothreadid_fromxml(vm, 0, id):
                logger.info("add iothread %d to guest config" % id)
                vm.addIOThread(id, libvirt.VIR_DOMAIN_AFFECT_CONFIG)
                if not find_iothreadid_fromxml(vm, 0, id):
                    logger.info("FAIL: cannot find iothread id in XML")
                    return 1

        logger.info("PASS: add iothread successful.")
    except libvirtError as e:
        logger.error("API error message: %s" % e.get_error_message())
        return 1
    return 0 
Example #16
Source File: numa_param_live.py    From libvirt-test-API with GNU General Public License v2.0 4 votes vote down vote up
def numa_param_live(params):
    """set domain numa parameters with live flag and check
    """
    global logger
    logger = params['logger']
    params.pop('logger')
    guestname = params['guestname']
    nodeset = params['nodeset']
    mode = int(params['mode'])

    logger.info("the name of virtual machine is %s" % guestname)
    logger.info("the given node number is: %s" % nodeset)
    logger.info("the given mode is: %s" % mode)

    global node_num
    cmd = "lscpu|grep 'NUMA node(s)'"
    ret, output = utils.exec_cmd(cmd, shell=True)
    node_num = int(output[0].split(' ')[-1])
    node_tuple = utils.param_to_tuple(nodeset, node_num)
    logger.debug("nodeset to tuple is:")
    logger.debug(node_tuple)

    param = {'numa_nodeset': nodeset, 'numa_mode': mode}
    logger.info("numa param dict for set is: %s" % param)

    conn = sharedmod.libvirtobj['conn']

    try:
        domobj = conn.lookupByName(guestname)
        logger.info("set domain numa parameters with flag: %s" %
                    libvirt.VIR_DOMAIN_AFFECT_LIVE)
        domobj.setNumaParameters(param, libvirt.VIR_DOMAIN_AFFECT_LIVE)
        logger.info("set domain numa parameters succeed")

        logger.info("check numa parameters")
        ret = domobj.numaParameters(libvirt.VIR_DOMAIN_AFFECT_LIVE)
        logger.info("numa parameters after set is: %s" % ret)

        new_tuple = utils.param_to_tuple(ret['numa_nodeset'], node_num)
        if not new_tuple:
            logger.error("fail to parse nodeset to tuple")
            return 1

        if new_tuple == node_tuple and ret['numa_mode'] == mode:
            logger.info("numa parameters is as expected")
        else:
            logger.error("numa parameters is not as expected")
            return 1

    except libvirtError as e:
        logger.error("libvirt call failed: " + str(e))
        return 1

    logger.info("check whether numa params is working")
    ret = check_numa_params(guestname, mode, node_tuple)
    if ret:
        logger.error("numa params working as expected")
        return 1
    else:
        logger.info("numa params working as expected")
        return 0 
Example #17
Source File: __init__.py    From kcli with Apache License 2.0 4 votes vote down vote up
def delete_nic(self, name, interface):
        conn = self.conn
        networks = {}
        nicnumber = 0
        for n in conn.listInterfaces():
            networks[n.name()] = 'bridge'
        for n in conn.listAllNetworks():
            networks[n.name()] = 'network'
        try:
            vm = conn.lookupByName(name)
            xml = vm.XMLDesc(0)
            root = ET.fromstring(xml)
        except:
            common.pprint("VM %s not found" % name, color='red')
            return {'result': 'failure', 'reason': "VM %s not found" % name}
        networktype, mac, source = None, None, None
        for element in list(root.getiterator('interface')):
            device = "eth%s" % nicnumber
            if device == interface:
                mac = element.find('mac').get('address')
                networktype = element.get('type')
                if networktype == 'bridge':
                    network = element.find('source').get('bridge')
                    source = "<source %s='%s'/>" % (networktype, network)
                else:
                    network = element.find('source').get('network')
                    source = "<source %s='%s'/>" % (networktype, network)
                break
            else:
                nicnumber += 1
        if networktype is None or mac is None or source is None:
            common.pprint("Interface %s not found" % interface, color='red')
            return {'result': 'failure', 'reason': "Interface %s not found" % interface}
        nicxml = """<interface type='%s'>
                    <mac address='%s'/>
                    %s
                    <model type='virtio'/>
                    </interface>""" % (networktype, mac, source)
        if self.debug:
            print(nicxml)
        # vm.detachDevice(nicxml)
        if vm.isActive() == 1:
            vm.detachDeviceFlags(nicxml, VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG)
        else:
            vm.detachDeviceFlags(nicxml, VIR_DOMAIN_AFFECT_CONFIG)
        vm = conn.lookupByName(name)
        vmxml = vm.XMLDesc(0)
        conn.defineXML(vmxml)
        return {'result': 'success'} 
Example #18
Source File: perf_events.py    From libvirt-test-API with GNU General Public License v2.0 4 votes vote down vote up
def check_events(events, guestname, flags, domstate, dom, logger):
    if utils.version_compare("libvirt-python", 3, 2, 0, logger):
        values = {'cmt': False, 'mbml': False, 'mbmt': False, 'cpu_cycles': False,
                  'instructions': False, 'cache_references': False,
                  'cache_misses': False, 'branch_instructions': False,
                  'branch_misses': False, 'bus_cycles': False,
                  'ref_cpu_cycles': False, 'stalled_cycles_backend': False,
                  'stalled_cycles_frontend': False, 'alignment_faults': False,
                  'context_switches': False, 'cpu_clock': False,
                  'cpu_migrations': False, 'emulation_faults': False,
                  'page_faults': False, 'page_faults_maj': False,
                  'page_faults_min': False, 'task_clock': False}
        event_list = ('cmt', 'mbmt', 'mbml', 'cpu_cycles', 'instructions',
                      'cache_references', 'cache_misses', 'branch_instructions',
                      'branch_misses', 'bus_cycles', 'ref_cpu_cycles',
                      'stalled_cycles_backend', 'stalled_cycles_frontend',
                      'alignment_faults', 'context_switches', 'cpu_clock',
                      'cpu_migrations', 'emulation_faults', 'page_faults',
                      'page_faults_maj', 'page_faults_min', 'task_clock')
    else:
        values = {'cmt': False, 'mbml': False, 'mbmt': False}
        event_list = ('cmt', 'mbmt', 'mbml')

    if ((domstate == libvirt.VIR_DOMAIN_RUNNING) and
        ((flags == libvirt.VIR_DOMAIN_AFFECT_CURRENT) or
         (flags == libvirt.VIR_DOMAIN_AFFECT_LIVE))):
        xmlstr = minidom.parse("%s%s.xml" % (XML_PATH, guestname))
    else:
        guestxml = dom.XMLDesc(libvirt.VIR_DOMAIN_XML_INACTIVE)
        xmlstr = minidom.parseString(guestxml)

    perf = xmlstr.getElementsByTagName('perf')
    if perf:
        perf = xmlstr.getElementsByTagName('perf')[0]
        for item in perf.getElementsByTagName('event'):
            for i in event_list:
                if item.getAttribute('name') == i:
                    if item.getAttribute('enabled') == "yes":
                        values[i] = True
                    elif item.getAttribute('enabled') == "no":
                        values[i] = False

    logger.info("values: %s" % values)
    for i in event_list:
        if values[i] != events[i]:
            return 1

    return 0 
Example #19
Source File: __init__.py    From kcli with Apache License 2.0 4 votes vote down vote up
def add_disk(self, name, size=1, pool=None, thin=True, image=None, shareable=False, existing=None,
                 interface='virtio'):
        conn = self.conn
        diskformat = 'qcow2'
        diskbus = interface
        if size < 1:
            common.pprint("Incorrect size.Leaving...", color='red')
            return {'result': 'failure', 'reason': "Incorrect size"}
        if not thin:
            diskformat = 'raw'
        try:
            vm = conn.lookupByName(name)
            xml = vm.XMLDesc(0)
            root = ET.fromstring(xml)
        except:
            common.pprint("VM %s not found" % name, color='red')
            return {'result': 'failure', 'reason': "VM %s not found" % name}
        currentdisk = 0
        diskpaths = []
        virtio_index, scsi_index, ide_index = 0, 0, 0
        for element in list(root.getiterator('disk')):
            disktype = element.get('device')
            device = element.find('target').get('dev')
            imagefiles = [element.find('source').get('file'), element.find('source').get('dev'),
                          element.find('source').get('volume')]
            path = next(item for item in imagefiles if item is not None)
            diskpaths.append(path)
            if disktype == 'cdrom':
                continue
            elif device.startswith('sd'):
                scsi_index += 1
            elif device.startswith('hd'):
                ide_index += 1
            else:
                virtio_index += 1
            currentdisk += 1
        diskindex = currentdisk
        if interface == 'scsi':
            diskdev = "sd%s" % string.ascii_lowercase[scsi_index]
        elif interface == 'ide':
            diskdev = "hd%s" % string.ascii_lowercase[ide_index]
        else:
            diskdev = "vd%s" % string.ascii_lowercase[virtio_index]
        if existing is None:
            storagename = "%s_%d.img" % (name, diskindex)
            diskpath = self.create_disk(name=storagename, size=size, pool=pool, thin=thin, image=image)
        elif existing in diskpaths:
            common.pprint("Disk %s already in VM %s" % (existing, name), color='blue')
            return {'result': 'success'}
        else:
            diskpath = existing
        diskxml = self._xmldisk(diskpath=diskpath, diskdev=diskdev, diskbus=diskbus, diskformat=diskformat,
                                shareable=shareable)
        if vm.isActive() == 1:
            vm.attachDeviceFlags(diskxml, VIR_DOMAIN_AFFECT_LIVE)
            vm = conn.lookupByName(name)
            vmxml = vm.XMLDesc(0)
            conn.defineXML(vmxml)
        else:
            vm.attachDeviceFlags(diskxml, VIR_DOMAIN_AFFECT_CONFIG)
        return {'result': 'success'} 
Example #20
Source File: info_iothread.py    From libvirt-test-API with GNU General Public License v2.0 4 votes vote down vote up
def info_iothread(params):
    """
       test API for ioThreadInfo in class virDomain
    """

    logger = params['logger']
    fail = 0

    if utils.check_qemu_package("qemu-kvm") and not utils.version_compare("qemu-kvm", 2, 12, 0, logger):
        logger.info("Current qemu-kvm don't support this API.")
        return 0

    try:
        conn = libvirt.open(params['conn'])

        logger.info("get connection to libvirtd")
        guest = params['guestname']
        vm = conn.lookupByName(guest)
        logger.info("test guest name: %s" % guest)

        """ test effect guest running XML """
        if vm.isActive() == 1:
            logger.info("guest is running test with running guest")

            ret = vm.ioThreadInfo(libvirt.VIR_DOMAIN_AFFECT_LIVE)

            if len(ret) == 0:
                vm.addIOThread(1, libvirt.VIR_DOMAIN_AFFECT_LIVE)
                if not find_iothreadid_fromxml(vm, 1, 1):
                    logger.info("FAIL: cannot find iothread id in XML")
                    return 1
                else:
                    ret = vm.ioThreadInfo(libvirt.VIR_DOMAIN_AFFECT_LIVE)

            for n in ret:
                if not find_iothreadid_fromxml(vm, 1, n[0]):
                    logger.info("FAIL: cannot find iothread id in XML")
                    fail = 1

        """ test effect guest config"""
        logger.info("test with guest inactive XML")
        ret = vm.ioThreadInfo(libvirt.VIR_DOMAIN_AFFECT_CONFIG)

        if len(ret) == 0:
            vm.addIOThread(1, libvirt.VIR_DOMAIN_AFFECT_CONFIG)
            if not find_iothreadid_fromxml(vm, 0, 1):
                logger.info("FAIL: cannot find iothread id in XML")
                return 1
            else:
                ret = vm.ioThreadInfo(libvirt.VIR_DOMAIN_AFFECT_CONFIG)

        for n in ret:
            if not find_iothreadid_fromxml(vm, 0, n[0]):
                logger.info("FAIL: cannot find iothread id in XML")
                fail = 1

    except libvirtError as e:
        logger.error("API error message: %s" % e.get_error_message())
        fail = 1
    return fail 
Example #21
Source File: set_memory_period.py    From libvirt-test-API with GNU General Public License v2.0 4 votes vote down vote up
def set_memory_period(params):
    """
       test API for setMemoryStatsPeriod in class virDomain
    """
    global logger
    logger = params['logger']
    fail = 0

    try:
        conn = libvirt.open(params['conn'])

        logger.info("get connection to libvirtd")
        guest = params['guestname']
        vm = conn.lookupByName(guest)
        logger.info("test guest name: %s" % guest)

        """ test with running vm """
        if vm.isActive() == 1:
            logger.info("guest is running, test with running guest")
            period = int(get_period_fromxml(vm, 1))
            if period == 0:
                vm.setMemoryStatsPeriod(1, libvirt.VIR_DOMAIN_AFFECT_LIVE)
                if int(get_period_fromxml(vm, 1)) != 1:
                    logger.error("Period value from xml is not right")
                    fail = 1
                elif check_memoryStats(vm) == 0:
                    period = 1
                else:
                    fail = 1

            if period > 0:
                if check_memoryStats(vm) == 0:
                    vm.setMemoryStatsPeriod(period + 1, libvirt.VIR_DOMAIN_AFFECT_LIVE)
                    if int(get_period_fromxml(vm, 1)) != period + 1:
                        logger.error("Period value from xml is not right")
                        fail = 1
                else:
                    fail = 1

        """ test with vm config """
        logger.info("guest is not running, test with config")
        period = int(get_period_fromxml(vm, 0))
        vm.setMemoryStatsPeriod(period + 1, libvirt.VIR_DOMAIN_AFFECT_CONFIG)
        if int(get_period_fromxml(vm, 0)) != period + 1:
            logger.error("Period value from xml is not right")
            fail = 1

    except libvirtError as e:
        logger.error("API error message: %s" % e.get_error_message())
        fail = 1
    return fail 
Example #22
Source File: host_thread.py    From openmano with Apache License 2.0 4 votes vote down vote up
def edit_iface(self, port_id, old_net, new_net):
        #This action imply remove and insert interface to put proper parameters
        if self.test:
            time.sleep(1)
        else:
        #get iface details
            self.db_lock.acquire()
            r,c = self.db.get_table(FROM='ports as p join resources_port as rp on p.uuid=rp.port_id',
                                    WHERE={'port_id': port_id})
            self.db_lock.release()
            if r<0:
                print self.name, ": edit_iface(",port_id,") DDBB error:", c
                return
            elif r==0:
                print self.name, ": edit_iface(",port_id,") por not found"
                return
            port=c[0]
            if port["model"]!="VF":
                print self.name, ": edit_iface(",port_id,") ERROR model must be VF"
                return
            #create xml detach file
            xml=[]
            self.xml_level = 2
            xml.append("<interface type='hostdev' managed='yes'>")
            xml.append("  <mac address='" +port['mac']+ "'/>")
            xml.append("  <source>"+ self.pci2xml(port['pci'])+"\n  </source>")
            xml.append('</interface>')                

            
            try:
                conn=None
                conn = libvirt.open("qemu+ssh://"+self.user+"@"+self.host+"/system")
                dom = conn.lookupByUUIDString(port["instance_id"])
                if old_net:
                    text="\n".join(xml)
                    print self.name, ": edit_iface detaching SRIOV interface", text
                    dom.detachDeviceFlags(text, flags=libvirt.VIR_DOMAIN_AFFECT_LIVE)
                if new_net:
                    xml[-1] ="  <vlan>   <tag id='" + str(port['vlan']) + "'/>   </vlan>"
                    self.xml_level = 1
                    xml.append(self.pci2xml(port.get('vpci',None)) )
                    xml.append('</interface>')                
                    text="\n".join(xml)
                    print self.name, ": edit_iface attaching SRIOV interface", text
                    dom.attachDeviceFlags(text, flags=libvirt.VIR_DOMAIN_AFFECT_LIVE)
                    
            except libvirt.libvirtError as e:
                text = e.get_error_message()
                print self.name, ": edit_iface(",port["instance_id"],") libvirt exception:", text 
                
            finally:
                if conn is not None: conn.close