Calendar _timestamp;
}
VmStatsEntry getVmStat(Connect conn, String vmName)
throws LibvirtException {
Domain dm = null;
try {
dm = getDomain(conn, vmName);
DomainInfo info = dm.getInfo();
VmStatsEntry stats = new VmStatsEntry();
stats.setNumCPUs(info.nrVirtCpu);
stats.setEntityType("vm");
/* get cpu utilization */
vmStats oldStats = null;
Calendar now = Calendar.getInstance();
oldStats = _vmStats.get(vmName);
long elapsedTime = 0;
if (oldStats != null) {
elapsedTime = now.getTimeInMillis()
- oldStats._timestamp.getTimeInMillis();
double utilization = (info.cpuTime - oldStats._usedTime)
/ ((double) elapsedTime * 1000000);
NodeInfo node = conn.nodeInfo();
utilization = utilization / node.cpus;
if(utilization > 0){
stats.setCPUUtilization(utilization * 100);
}
}
/* get network stats */
List<InterfaceDef> vifs = getInterfaces(conn, vmName);
long rx = 0;
long tx = 0;
for (InterfaceDef vif : vifs) {
DomainInterfaceStats ifStats = dm.interfaceStats(vif
.getDevName());
rx += ifStats.rx_bytes;
tx += ifStats.tx_bytes;
}
if (oldStats != null) {
double deltarx = rx - oldStats._rx;
if (deltarx > 0)
stats.setNetworkReadKBs(deltarx / 1024);
double deltatx = tx - oldStats._tx;
if (deltatx > 0)
stats.setNetworkWriteKBs(deltatx / 1024);
}
/* get disk stats */
List<DiskDef> disks = getDisks(conn, vmName);
long io_rd = 0;
long io_wr = 0;
long bytes_rd = 0;
long bytes_wr = 0;
for (DiskDef disk : disks) {
DomainBlockStats blockStats = dm.blockStats(disk.getDiskLabel());
io_rd += blockStats.rd_req;
io_wr += blockStats.wr_req;
bytes_rd += blockStats.rd_bytes;
bytes_wr += blockStats.wr_bytes;
}
if (oldStats != null) {
long deltaiord = io_rd - oldStats._io_rd;
if (deltaiord > 0)
stats.setDiskReadIOs(deltaiord);
long deltaiowr = io_wr - oldStats._io_wr;
if (deltaiowr > 0)
stats.setDiskWriteIOs(deltaiowr);
double deltabytesrd = bytes_rd - oldStats._bytes_rd;
if (deltabytesrd > 0)
stats.setDiskReadKBs(deltabytesrd / 1024);
double deltabyteswr = bytes_wr - oldStats._bytes_wr;
if (deltabyteswr > 0)
stats.setDiskWriteKBs(deltabyteswr / 1024);
}
/* save to Hashmap */
vmStats newStat = new vmStats();
newStat._usedTime = info.cpuTime;
newStat._rx = rx;
newStat._tx = tx;
newStat._io_rd = io_rd;
newStat._io_wr = io_wr;
newStat._bytes_rd = bytes_rd;
newStat._bytes_wr = bytes_wr;
newStat._timestamp = now;
_vmStats.put(vmName, newStat);
return stats;
} finally {
if (dm != null) {
dm.free();
}
}
}