#! /usr/bin/python
from re import T
import libvirt
import json
import sys
import time
# CPU memory data
def memory_usage(hname='host1',kvmname='vm1'):
if hname=='host1':
conn=libvirt.open("qemu+ssh://192.168.43.12/system")
else:
conn = libvirt.open("qemu:///system")
info = {}
dom = conn.lookupByName(kvmname)
dom.setMemoryStatsPeriod(10)
# memory usage
meminfo = dom.memoryStats()
free_mem = float(meminfo['unused'])
total_mem = float(meminfo['available'])
used_mem = total_mem-free_mem
mem_usage = round(((total_mem-free_mem) / total_mem)*100, 2)
info['mem_usage'] = mem_usage
info['mem_used'] = round(used_mem/1024/1024, 2)
info['mem_total'] = round(total_mem/1024/1024, 2)
info['mem_free'] = round(free_mem/1024/1024, 2)
return json.dumps(info['mem_usage'])
# while(True):
# print(memory_usage())
# CPU memory data
def cpu_usage(hname='host1',kvmname='vm1'):
if hname=='host1':
conn=libvirt.open("qemu+ssh://192.168.43.12/system")
else:
conn = libvirt.open("qemu:///system")
info = {}
dom = conn.lookupByName(kvmname)
dom.setMemoryStatsPeriod(10)
# cpu usage
t1 = time.time()
c1 = int(dom.info()[4])
time.sleep(0.1)
t2 = time.time()
c2 = int(dom.info()[4])
c_nums = int(dom.info()[3])
cpu_usage = round((c2 - c1) * 100 / ((t2 - t1) * c_nums * 1e9), 2)
if cpu_usage>100:
cpu_usage=100
info['cpu_usage'] = cpu_usage
print(info)
return json.dumps(info['cpu_usage'])
# while(True):
# print(cpu_usage())