I first met OpenStack for two weeks. After the layers of veils were removed, I gradually realized its power. I was determined to use it as a sword to fight the battlefield of cloud computing. Tonight, the horn sounded and the preface was played. .
After creating virtual instances with OpenStack, you need to monitor these instances . This article is about using the Libvirt API integrated with OpenStack to monitor the CPU, memory, disk usage, and network upload and download speed of the virtual machine in the KVM environment .
Stop gossip and get straight to the point.
1 Monitoring of the CPU
Python code
import libvirt
import os
import time
conn=libvirt.open( "qemu:///system" )
if conn==None:
print "fail to connect hypervisor"
sys.exit( 1 )
try :
dom0=conn.lookupByID( 85 ) #Get the corresponding Domain object according to the Instance ID created by OpenStack
except :
print "fail to find the domain by ID"
sys.exit( 1 )
Pstart_time=time.time() #Get the current time
Dstart_time=dom0.info()[ 4 ]#Get the CPU time information in
DomainInfo directly time.sleep( 2 )
Dstop_time=dom0.info()[ 4 ]
Pstop_time=time.time()
core_num=int(dom0.info()[ 3 ])#Get the core number information in DomainIndo
# CPU utilization calculation formula - CPU time difference/time interval/1000000000/number of cores*100= CPU utilization
cpu _usage=(Dstart_time-Dstop_time)/(Pstart_time-Pstop_time)/ 1000000000 /core_num* 100
cpu _usage= cpu _usage if ( cpu _usage> 0 ) else 0.0
cpu _usage= cpu _usage if ( cpu _usage< 100 ) else 100.0
print cpu _usage
2 Monitoring of memory
python code
def get_memory (pid): #Define the function to get the currently used memory
mem= 0
#Linux under /proc/pid (process ID)/smaps stores the process memory image information, which is more detailed than the maps file in the same directory
for line in file('/proc/%d/smaps' % int(pid),'r'):
if re.findall('Private_',line):
#Statistics of Private memory information
mem+= int (re.findall( '(\d+)' ,line)[ 0 ])
return mem
#Get the process ID according to the instance name
pid=(os.popen("ps aux|grep "+dom0.name()+" | grep -v 'grep' | awk '{print $2}'").readlines()[0])
memstatus=get_memory(pid)
memusage='%.2f' % (int(memstatus)*100.0/int(dom0.info()[2]))
print memusage
Verification method: You can SSH to the corresponding virtual instance. If it is a Linux system, you can use the free -m command to check the memory usage.
3 Monitoring of disks
When creating a virtual machine application instance, a corresponding XML file will be generated to indicate the instance information
def get_devices ( dom , path , devs ): #This function is used to get the value of a node in XML
tree=ElementTree.fromstring(dom.XMLDesc( 0 ))#Convert XML file to XML tree object
devices=[]
for target in tree.findall(path):
dev=target.get(devs)
if not dev in devices:
devices.append(dev)
return devices
def get_blockStats (dom):#The function of getting disk status information includes the total number of bits read in and the total number of bits written out
block_status={}
disks=get_devices(dom, "devices/disk/target" , "dev" )
for block in disks:
block_status[block]=dom.blockStats(block)
return block_status
block_status0={}
block_status1={}
block_status0=get_blockStats(dom0)
time.sleep(2)
block_status1=get_blockStats(dom0)
block_info=[]
for block in get_devices(dom0,"devices/disk/source","file"):
block_info.append(dom0.blockInfo(block,0))#获取磁盘信息 其中0为默认传入的参数
for domBlockInfo in block_info:
print "logical size in bytes :%s" % domBlockInfo[0]
print "highest allocated extent in bytes :%s" % domBlockInfo[1]
print "physical size in bytes :%s" % domBlockInfo[2]
print "disk usage :%s" % str(domBlockInfo[1]/1.0/domBlockInfo[0]*100)[:5]
for block in get_devices(dom0,"devices/disk/target","dev"):
print "rd_speed :%s" % str((block_status1[block][1]-block_status0[block][1])/2048)
print "wr_speed :%s" % str((block_status1[block][3]-block_status0[block][3])/2048)
Verification method: You can SSH to the corresponding virtual instance. If it is a Linux system, you can use the df -h command to view the disk usage.
4 Monitoring the network
def get_nicInfo (nics):#Get network information including the total number of bits of Receive and the total number of bits of Transmit
net_status={}
#View network information through cat /proc/net/dev command
for nic in nics:
net_status[nic]=[os.popen( "cat /proc/net/dev |grep -w '" +nic+ "' |awk '{ print $10}'" ).readlines()[ 0 ][:- 1 ],os.popen( "cat /proc/net/dev |grep -w '" +nic+ "' |awk '{print $2}'" ).readlines()[ 0 ][:- 1 ]]
return net_status
net_status0={}
net_status1={}
#获取网卡名称
nics=get_devices(dom0,"devices/interface/target","dev")
net_status0=get_nicInfo(nics)
time.sleep(2)
net_status1=get_nicInfo(nics)
for nic in nics:
print "netcard_name :%s" % nic
print "transmit_speed :%s" % str((int(net_status1[nic][0])-int(net_status0[nic][0]))/2048)
print "receive_speed :%s" % str((int(net_status1[nic][1])-int(net_status0[nic][1]))/2048)
It's the first time to write a blog, please be merciful, please spray lightly!
refer to:
Libvirt official website API definition
virDomainBlockInfo
struct virDomainBlockInfo {
unsigned long long | capacity | logical size in bytes of the block device backing image |
unsigned long long | allocation | highest allocated extent in bytes of the block device backing image |
unsigned long long | physical | physical size in bytes of the container of the backing image |
}
virDomainBlockStatsStruct
struct virDomainBlockStatsStruct {
long long | rd_req | number of read requests |
long long | rd_bytes | number of read bytes |
long long | wr_req | number of write requests |
long long | wr_bytes | number of written bytes |
long long | errs | In Xen this returns the mysterious 'oo_req'. |
}