Example #1
0
 def setPollInterval(self):
     setPollIntervalCommand = {
             'execute':'qom-set',
             'arguments':{
                 'path':'/machine/peripheral/balloon0',
                 'property':'guest-stats-polling-interval',
                 'value':2
                 }
             }
     try:
         libvirt_qemu.qemuMonitorCommand(self.domain,
             json.dumps(setPollIntervalCommand), 0)
     except Exception as e:
         errorlogger.exception("name: %s, uuid: %s, Unable to set poll interval",
             self.domName, self.uuid)
Example #2
0
def block_job_progress(dom):
    while True:
        info = json.loads(
            qemuMonitorCommand(dom, '{"execute":"query-block-jobs"}', 0))
        if len(info['return']) == 0:
            break

        bar_length = 50
        for i in info['return']:
            start = i['offset']
            end = i['len']
            percent = float(start) / float(end)
            hashes = '#' * int(round(percent * bar_length))
            spaces = '-' * (bar_length - len(hashes))
            stdout.write("\r[{0}] {1}/{2} ({3}%)".format(
                hashes + spaces, start, end, int(round(percent * 100))))
            stdout.flush()
            sleep(2)
        start = end
        percent = float(start) / float(end)
        hashes = '#' * int(round(percent * bar_length))
        spaces = '-' * (bar_length - len(hashes))
        stdout.write("\r[{0}] {1}/{2} ({3}%)".format(
            hashes + spaces, start, end, int(round(percent * 100))))
        stdout.flush()
    stdout.write("!\n")
Example #3
0
 def _qemu_monitor(self, command):
     self.message("& " + command)
     # you can run commands manually using virsh:
     # virsh -c qemu:///session qemu-monitor-command [domain name/id] --hmp [command]
     output = libvirt_qemu.qemuMonitorCommand(self._domain, command, libvirt_qemu.VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP)
     self.message(output.strip())
     return output
Example #4
0
 def _qemu_monitor(self, command):
     self.message("& " + command)
     # you can run commands manually using virsh:
     # virsh -c qemu:///session qemu-monitor-command [domain name/id] --hmp [command]
     output = libvirt_qemu.qemuMonitorCommand(self._domain, command, libvirt_qemu.VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP)
     self.message(output.strip())
     return output
Example #5
0
def is_cdrom_tray_open(domain):
    """
    Returns True if even one CD-ROM tray is open.
    """
    res = libvirt_qemu.qemuMonitorCommand(
        domain,
        json.dumps(
            {'execute': 'query-block'},
            ),
        # TODO should force this to be qmp, but python-libvirt 0.9.8
        # doesn't seem to be able to do that
        libvirt_qemu.VIR_DOMAIN_QEMU_MONITOR_COMMAND_DEFAULT,
        )
    res = json.loads(res)
    if 'error' in res:
        raise exc.DownburstError(
            'Cannot query QEmu for block device state',
            res['error'].get('desc'),
            )

    cdroms = [dev for dev in res['return'] if 'tray_open' in dev]
    if not cdroms:
        raise exc.DownburstError(
            'VM must have at least one CD-ROM to check tray status',
            res['error'].get('desc'),
            )

    for dev in cdroms:
        if dev['tray_open']:
            return True

    return False
Example #6
0
def is_cdrom_tray_open(domain):
    """
    Returns True if even one CD-ROM tray is open.
    """
    res = libvirt_qemu.qemuMonitorCommand(
        domain,
        json.dumps(
            {'execute': 'query-block'},
            ),
        # TODO should force this to be qmp, but python-libvirt 0.9.8
        # doesn't seem to be able to do that
        libvirt_qemu.VIR_DOMAIN_QEMU_MONITOR_COMMAND_DEFAULT,
        )
    res = json.loads(res)
    if 'error' in res:
        raise exc.DownburstError(
            'Cannot query QEmu for block device state',
            res['error'].get('desc'),
            )

    cdroms = [dev for dev in res['return'] if 'tray_open' in dev]
    if not cdroms:
        raise exc.DownburstError(
            'VM must have at least one CD-ROM to check tray status',
            res['error'].get('desc'),
            )

    for dev in cdroms:
        if dev['tray_open']:
            return True

    return False
Example #7
0
 def setPollInterval(self):
     setPollIntervalCommand = {
         'execute': 'qom-set',
         'arguments': {
             'path': '/machine/peripheral/balloon0',
             'property': 'guest-stats-polling-interval',
             'value': 2
         }
     }
     try:
         libvirt_qemu.qemuMonitorCommand(self.domain,
                                         json.dumps(setPollIntervalCommand),
                                         0)
     except Exception as e:
         errorlogger.exception(
             "name: %s, uuid: %s, Unable to set poll interval",
             self.domName, self.uuid)
Example #8
0
 def getvCpuPid(self):
     command = {
         'execute': 'query-cpus',
     }
     try:
         out = libvirt_qemu.qemuMonitorCommand(self.domain, json.dumps(command), 0)
         out = json.loads(out)
         for cpu in out['return']:
             self.vCpuPid.append(str(cpu['thread_id']))
     except Exception as e:
         errorlogger.exception("name: %s, uuid: %s, Unable to get vCpuPid",
             self.domName, self.uuid)
Example #9
0
 def getvCpuPid(self):
     command = {
         'execute': 'query-cpus',
     }
     try:
         out = libvirt_qemu.qemuMonitorCommand(self.domain,
                                               json.dumps(command), 0)
         out = json.loads(out)
         for cpu in out['return']:
             self.vCpuPid.append(str(cpu['thread_id']))
     except Exception as e:
         errorlogger.exception("name: %s, uuid: %s, Unable to get vCpuPid",
                               self.domName, self.uuid)
Example #10
0
    def quota(guest=None, msg=None):
        assert isinstance(guest, libvirt.virDomain)
        assert isinstance(msg, dict)

        for disk in msg['disks']:
            libvirt_qemu.qemuMonitorCommand(guest, json.dumps({
                    'execute': 'block_set_io_throttle',
                    'arguments': {
                        'device': 'drive-virtio-disk' + str(disk['sequence']),
                        'iops': int(disk['iops']),
                        'iops_rd': int(disk['iops_rd']),
                        'iops_wr': int(disk['iops_wr']),
                        'iops_max': int(disk['iops_max']),
                        'iops_max_length': int(disk['iops_max_length']),
                        'bps': int(disk['bps']),
                        'bps_rd': int(disk['bps_rd']),
                        'bps_wr': int(disk['bps_wr']),
                        'bps_max': int(disk['bps_max']),
                        'bps_max_length': int(disk['bps_max_length'])
                    }
                }),
                libvirt_qemu.VIR_DOMAIN_QEMU_MONITOR_COMMAND_DEFAULT)
Example #11
0
    def test_monitor(self):
        #print self.virt_domain.monitor()
        #print self.virt_domain.domain.vcpus()

        #print self.virt_domain.domain.memoryStats()
        #print self.virt_domain.domain.maxMemory()
        #print self.virt_domain.domain.maxVcpus()
        #print self.virt_domain.conn.getCPUStats(0)
        #print self.virt_domain.conn.getFreeMemory()
        #print self.virt_domain.conn.getMaxVcpus()
        #print self.virt_domain.conn.listNetworks()

        import libvirt_qemu
        #libvirt_qemu.qemuAgentCommand(domain, cmd, timeout, flags)

        #res = libvirt_qemu.qemuMonitorCommand(self.virt_domain.domain, '{ "execute": "query-commands" }',
        #                                      libvirt_qemu.VIR_DOMAIN_QEMU_MONITOR_COMMAND_DEFAULT)
        #data = json.loads(res)
        #self.pp.pprint(data)

        print libvirt_qemu.qemuMonitorCommand(
            self.virt_domain.domain, '{ "execute": "query-vnc" }',
            libvirt_qemu.VIR_DOMAIN_QEMU_MONITOR_COMMAND_DEFAULT)
Example #12
0
 def vnc_connection_status(self):
     """Return vnc connection channels
     
     :return: list of spice connection channels
     """
     try:
         stat = libvirt_qemu.qemuMonitorCommand(
             self._domain, '{ "execute": "query-vnc" }',
             libvirt_qemu.VIR_DOMAIN_QEMU_MONITOR_COMMAND_DEFAULT)
         self.switch()
         data = json.loads(stat)['return']['clients']
         self.logger.debug('Get spice connection status: %s' % data)
     except libvirt.libvirtError, ex:
         self.logger.error(ex)
         raise VirtDomainError(ex)
Example #13
0
 def getMemoryStats(self):
     memStatsCommand = {
             'execute': 'qom-get',
             'arguments': {
                 'path':'/machine/peripheral/balloon0',
                 'property':'guest-stats',
                 }
             }
     try:
         out = libvirt_qemu.qemuMonitorCommand(self.domain,
             json.dumps(memStatsCommand), 0)
         out = json.loads(out)
         if self.timestamp < out['return']['last-update']:
             self.stats = self.toMb(out['return']['stats'])
         #self.log('stats: %s', self.stats)
     except Exception as e:
         errorlogger.exception("name: %s, uuid: %s, Unable to get stats",
             self.domName, self.uuid)
Example #14
0
def check_iothreadpin(vm, iothreadid, cpuset):
    ret = libvirt_qemu.qemuMonitorCommand(vm, '{ "execute": "query-iothreads" }', 0)
    tid = get_qmp_return_iothread(ret, iothreadid)
    if not tid:
        return False

    cmds = "taskset --cpu-list -p %d| awk {'print $6'}" % tid
    (status, output) = utils.exec_cmd(cmds, shell=True)
    if status != 0:
        logger.info("Exec_cmd failed: %s" % cmds)
        return False

    logger.info("cpuset from taskset is %s" % output[0])
    if output[0] != cpuset:
        logger.info("Cpuset is not equal: taskset is %s and libvirt is %s" % (output, cpuset))
        return False

    return True
Example #15
0
 def getMemoryStats(self):
     memStatsCommand = {
         'execute': 'qom-get',
         'arguments': {
             'path': '/machine/peripheral/balloon0',
             'property': 'guest-stats',
         }
     }
     try:
         out = libvirt_qemu.qemuMonitorCommand(self.domain,
                                               json.dumps(memStatsCommand),
                                               0)
         out = json.loads(out)
         if self.timestamp < out['return']['last-update']:
             self.stats = self.toMb(out['return']['stats'])
         #self.log('stats: %s', self.stats)
     except Exception as e:
         errorlogger.exception("name: %s, uuid: %s, Unable to get stats",
                               self.domName, self.uuid)
def check_iothreadpin(vm, iothreadid, cpuset):
    ret = libvirt_qemu.qemuMonitorCommand(vm,
                                          '{ "execute": "query-iothreads" }',
                                          0)
    tid = get_qmp_return_iothread(ret, iothreadid)
    if not tid:
        return False

    cmds = "taskset --cpu-list -p %d| awk {'print $6'}" % tid
    (status, output) = utils.exec_cmd(cmds, shell=True)
    if status != 0:
        logger.info("Exec_cmd failed: %s" % cmds)
        return False

    logger.info("cpuset from taskset is %s" % output[0])
    if output[0] != cpuset:
        logger.info("Cpuset is not equal: taskset is %s and libvirt is %s" %
                    (output, cpuset))
        return False

    return True
Example #17
0
    def _native_command(self, command, **kwargs):
        """
        Invoke a command directly on the virtual machine manager.

        This method is unsafe, in that it allows a developer to bypass
        the integrity checks of the virtualisation platform.  It should
        be used sparingly, and only where there is no alternative.

        Arguments:
        command -- the name of the command to invoke.
        """
        message = json.dumps({"execute": command, "arguments": kwargs})
        data = libvirt_qemu.qemuMonitorCommand(self.domain, message, 0)
        try:
            response = json.loads(data)
            if "return" in response:
                return response["return"]
            else:
                logger.critical("Unknown response from console: %s", response)
                raise RuntimeError("Unknown response from console")
        except TypeError:
            raise RuntimeError("Malformed message from virtual machine")
Example #18
0
    def _native_command(self, command, **kwargs):
        """
        Invoke a command directly on the virtual machine manager.

        This method is unsafe, in that it allows a developer to bypass
        the integrity checks of the virtualisation platform.  It should
        be used sparingly, and only where there is no alternative.

        Arguments:
        command -- the name of the command to invoke.
        """
        message = json.dumps({"execute": command, "arguments": kwargs})
        data = libvirt_qemu.qemuMonitorCommand(self.domain, message, 0)
        try:
            response = json.loads(data)
            if "return" in response:
                return response["return"]
            else:
                logger.critical("Unknown response from console: %s", response)
                raise RuntimeError("Unknown response from console")
        except TypeError:
            raise RuntimeError("Malformed message from virtual machine")
Example #19
0
def exec_monitor_command(inst, execute_str: str):
    query_results = json.loads(qemuMonitorCommand(inst, execute_str, 0))
    #if len(query_results['return']) == 0:
    #    return None
    return query_results
Example #20
0
def exec_monitor_command(dom: Domain, execute_str: str):
    query_results = json.loads(qemuMonitorCommand(dom, execute_str, 0))
    if len(query_results['return']) == 0:
        return None
    return query_results
Example #21
0
def check_active_progress(dom):
    info = json.loads(
        qemuMonitorCommand(dom, '{"execute":"query-block-jobs"}', 0))
    if len(info['return']) == 0:
        return False
    return True
Example #22
0
 def exec_mon_cmd(self, cmd_str_list: list):
     for cmd_str in cmd_str_list:
         logging.debug("Execution :", cmd_str)
         q_results = json.loads(qemuMonitorCommand(self.dom, cmd_str, 0))
     return q_results