use of com.cloud.hypervisor.kvm.resource.xml.LibvirtDiskDef in project cosmic by MissionCriticalCloud.
the class LibvirtComputingResource method getVmDiskStat.
public List<VmDiskStatsEntry> getVmDiskStat(final Connect conn, final String vmName) throws LibvirtException {
Domain dm = null;
try {
dm = getDomain(conn, vmName);
final List<VmDiskStatsEntry> stats = new ArrayList<>();
final List<LibvirtDiskDef> disks = getDisks(conn, vmName);
for (final LibvirtDiskDef disk : disks) {
if (disk.getDeviceType() != DeviceType.DISK) {
break;
}
final DomainBlockStats blockStats = dm.blockStats(disk.getDiskLabel());
// for example, path = /mnt/pool_uuid/disk_path/
final String path = disk.getDiskPath();
String diskPath = null;
if (path != null) {
final String[] token = path.split("/");
if (token.length > 3) {
diskPath = token[3];
final VmDiskStatsEntry stat = new VmDiskStatsEntry(vmName, diskPath, blockStats.wr_req, blockStats.rd_req, blockStats.wr_bytes, blockStats.rd_bytes);
stats.add(stat);
}
}
}
return stats;
} finally {
if (dm != null) {
dm.free();
}
}
}
use of com.cloud.hypervisor.kvm.resource.xml.LibvirtDiskDef in project cosmic by MissionCriticalCloud.
the class LibvirtComputingResource method getVmStat.
public VmStatsEntry getVmStat(final Connect conn, final String vmName) throws LibvirtException {
Domain dm = null;
try {
dm = getDomain(conn, vmName);
final DomainInfo info = dm.getInfo();
final VmStatsEntry stats = new VmStatsEntry();
stats.setNumCPUs(info.nrVirtCpu);
stats.setEntityType("vm");
/* get cpu utilization */
VmStats oldStats = null;
final 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);
final NodeInfo node = conn.nodeInfo();
utilization = utilization / node.cpus;
if (utilization > 0) {
stats.setCPUUtilization(utilization * 100);
}
}
/* get network stats */
final List<InterfaceDef> vifs = getInterfaces(conn, vmName);
long rx = 0;
long tx = 0;
for (final InterfaceDef vif : vifs) {
final DomainInterfaceStats ifStats = dm.interfaceStats(vif.getDevName());
rx += ifStats.rx_bytes;
tx += ifStats.tx_bytes;
}
if (oldStats != null) {
final double deltarx = rx - oldStats.rx;
if (deltarx > 0) {
stats.setNetworkReadKBs(deltarx / 1024);
}
final double deltatx = tx - oldStats.tx;
if (deltatx > 0) {
stats.setNetworkWriteKBs(deltatx / 1024);
}
}
/* get disk stats */
final List<LibvirtDiskDef> disks = getDisks(conn, vmName);
long ioRd = 0;
long ioWr = 0;
long bytesRd = 0;
long bytesWr = 0;
for (final LibvirtDiskDef disk : disks) {
if (disk.getDeviceType() == DeviceType.CDROM || disk.getDeviceType() == DeviceType.FLOPPY) {
continue;
}
final DomainBlockStats blockStats = dm.blockStats(disk.getDiskLabel());
ioRd += blockStats.rd_req;
ioWr += blockStats.wr_req;
bytesRd += blockStats.rd_bytes;
bytesWr += blockStats.wr_bytes;
}
if (oldStats != null) {
final long deltaiord = ioRd - oldStats.ioRead;
if (deltaiord > 0) {
stats.setDiskReadIOs(deltaiord);
}
final long deltaiowr = ioWr - oldStats.ioWrote;
if (deltaiowr > 0) {
stats.setDiskWriteIOs(deltaiowr);
}
final double deltabytesrd = bytesRd - oldStats.bytesRead;
if (deltabytesrd > 0) {
stats.setDiskReadKBs(deltabytesrd / 1024);
}
final double deltabyteswr = bytesWr - oldStats.bytesWrote;
if (deltabyteswr > 0) {
stats.setDiskWriteKBs(deltabyteswr / 1024);
}
}
/* save to Hashmap */
final VmStats newStat = new VmStats();
newStat.usedTime = info.cpuTime;
newStat.rx = rx;
newStat.tx = tx;
newStat.ioRead = ioRd;
newStat.ioWrote = ioWr;
newStat.bytesRead = bytesRd;
newStat.bytesWrote = bytesWr;
newStat.timestamp = now;
vmStats.put(vmName, newStat);
return stats;
} finally {
if (dm != null) {
dm.free();
}
}
}
use of com.cloud.hypervisor.kvm.resource.xml.LibvirtDiskDef in project cosmic by MissionCriticalCloud.
the class LibvirtComputingResource method attachOrDetachIso.
public synchronized String attachOrDetachIso(final Connect conn, final String vmName, String isoPath, final boolean isAttach) throws LibvirtException, URISyntaxException, InternalErrorException {
String isoXml = null;
if (isoPath != null && isAttach) {
final int index = isoPath.lastIndexOf("/");
final String path = isoPath.substring(0, index);
final String name = isoPath.substring(index + 1);
final KvmStoragePool secondaryPool = storagePoolMgr.getStoragePoolByUri(path);
final KvmPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name);
isoPath = isoVol.getPath();
final LibvirtDiskDef iso = new LibvirtDiskDef();
iso.defIsoDisk(isoPath);
isoXml = iso.toString();
} else {
final LibvirtDiskDef iso = new LibvirtDiskDef();
iso.defIsoDisk(null);
isoXml = iso.toString();
}
final List<LibvirtDiskDef> disks = getDisks(conn, vmName);
final String result = attachOrDetachDevice(conn, true, vmName, isoXml);
if (result == null && !isAttach) {
for (final LibvirtDiskDef disk : disks) {
if (disk.getDeviceType() == LibvirtDiskDef.DeviceType.CDROM) {
cleanupDisk(disk);
}
}
}
return result;
}
use of com.cloud.hypervisor.kvm.resource.xml.LibvirtDiskDef in project cosmic by MissionCriticalCloud.
the class LibvirtDomainXmlParser method parseDomainXml.
public boolean parseDomainXml(final String domXml) {
final DocumentBuilder builder;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final InputSource is = new InputSource();
is.setCharacterStream(new StringReader(domXml));
final Document doc = builder.parse(is);
final Element rootElement = doc.getDocumentElement();
desc = getTagValue("description", rootElement);
final Element devices = (Element) rootElement.getElementsByTagName("devices").item(0);
final NodeList disks = devices.getElementsByTagName("disk");
for (int i = 0; i < disks.getLength(); i++) {
final Element disk = (Element) disks.item(i);
final String type = disk.getAttribute("type");
final LibvirtDiskDef def = new LibvirtDiskDef();
if (type.equalsIgnoreCase("network")) {
final String diskFmtType = getAttrValue("driver", "type", disk);
final String diskCacheMode = getAttrValue("driver", "cache", disk);
final String diskPath = getAttrValue("source", "name", disk);
final String protocol = getAttrValue("source", "protocol", disk);
final String authUserName = getAttrValue("auth", "username", disk);
final String poolUuid = getAttrValue("secret", "uuid", disk);
final String host = getAttrValue("host", "name", disk);
final int port = Integer.parseInt(getAttrValue("host", "port", disk));
final String diskLabel = getAttrValue("target", "dev", disk);
final String bus = getAttrValue("target", "bus", disk);
LibvirtDiskDef.DiskFmtType fmt = null;
if (diskFmtType != null) {
fmt = LibvirtDiskDef.DiskFmtType.valueOf(diskFmtType.toUpperCase());
}
def.defNetworkBasedDisk(diskPath, host, port, authUserName, poolUuid, diskLabel, LibvirtDiskDef.DiskBus.valueOf(bus.toUpperCase()), LibvirtDiskDef.DiskProtocol.valueOf(protocol.toUpperCase()), fmt);
def.setCacheMode(LibvirtDiskDef.DiskCacheMode.valueOf(diskCacheMode.toUpperCase()));
} else {
final String diskFmtType = getAttrValue("driver", "type", disk);
final String diskCacheMode = getAttrValue("driver", "cache", disk);
final String diskFile = getAttrValue("source", "file", disk);
final String diskDev = getAttrValue("source", "dev", disk);
final String diskLabel = getAttrValue("target", "dev", disk);
final String bus = getAttrValue("target", "bus", disk);
final String device = disk.getAttribute("device");
if (type.equalsIgnoreCase("file")) {
if (device.equalsIgnoreCase("disk")) {
LibvirtDiskDef.DiskFmtType fmt = null;
if (diskFmtType != null) {
fmt = LibvirtDiskDef.DiskFmtType.valueOf(diskFmtType.toUpperCase());
}
def.defFileBasedDisk(diskFile, diskLabel, LibvirtDiskDef.DiskBus.valueOf(bus.toUpperCase()), fmt);
} else if (device.equalsIgnoreCase("cdrom")) {
def.defIsoDisk(diskFile);
}
} else if (type.equalsIgnoreCase("block")) {
def.defBlockBasedDisk(diskDev, diskLabel, LibvirtDiskDef.DiskBus.valueOf(bus.toUpperCase()));
}
if (diskCacheMode != null) {
def.setCacheMode(LibvirtDiskDef.DiskCacheMode.valueOf(diskCacheMode.toUpperCase()));
}
}
final NodeList iotune = disk.getElementsByTagName("iotune");
if (iotune != null && iotune.getLength() != 0) {
final String bytesReadRateStr = getTagValue("read_bytes_sec", (Element) iotune.item(0));
if (bytesReadRateStr != null) {
final Long bytesReadRate = Long.parseLong(bytesReadRateStr);
def.setBytesReadRate(bytesReadRate);
}
final String bytesWriteRateStr = getTagValue("write_bytes_sec", (Element) iotune.item(0));
if (bytesWriteRateStr != null) {
final Long bytesWriteRate = Long.parseLong(bytesWriteRateStr);
def.setBytesWriteRate(bytesWriteRate);
}
final String iopsReadRateStr = getTagValue("read_iops_sec", (Element) iotune.item(0));
if (iopsReadRateStr != null) {
final Long iopsReadRate = Long.parseLong(iopsReadRateStr);
def.setIopsReadRate(iopsReadRate);
}
final String iopsWriteRateStr = getTagValue("write_iops_sec", (Element) iotune.item(0));
if (iopsWriteRateStr != null) {
final Long iopsWriteRate = Long.parseLong(iopsWriteRateStr);
def.setIopsWriteRate(iopsWriteRate);
}
}
diskDefs.add(def);
}
final NodeList nics = devices.getElementsByTagName("interface");
for (int i = 0; i < nics.getLength(); i++) {
final Element nic = (Element) nics.item(i);
final String type = nic.getAttribute("type");
final String mac = getAttrValue("mac", "address", nic);
final String dev = getAttrValue("target", "dev", nic);
final String model = getAttrValue("model", "type", nic);
final InterfaceDef def = new InterfaceDef();
final NodeList bandwidth = nic.getElementsByTagName("bandwidth");
Integer networkRateKBps = 0;
if (bandwidth != null && bandwidth.getLength() != 0) {
final Integer inbound = Integer.valueOf(getAttrValue("inbound", "average", (Element) bandwidth.item(0)));
final Integer outbound = Integer.valueOf(getAttrValue("outbound", "average", (Element) bandwidth.item(0)));
if (inbound.equals(outbound)) {
networkRateKBps = inbound;
}
}
if (type.equalsIgnoreCase("network")) {
final String network = getAttrValue("source", "network", nic);
def.defPrivateNet(network, dev, mac, NicModel.valueOf(model.toUpperCase()), networkRateKBps);
} else if (type.equalsIgnoreCase("bridge")) {
final String bridge = getAttrValue("source", "bridge", nic);
def.defBridgeNet(bridge, dev, mac, NicModel.valueOf(model.toUpperCase()), networkRateKBps);
} else if (type.equalsIgnoreCase("ethernet")) {
final String scriptPath = getAttrValue("script", "path", nic);
def.defEthernet(dev, mac, NicModel.valueOf(model.toUpperCase()), scriptPath, networkRateKBps);
}
interfaces.add(def);
}
final Element graphic = (Element) devices.getElementsByTagName("graphics").item(0);
if (graphic != null) {
final String port = graphic.getAttribute("port");
if (port != null) {
try {
vncPort = Integer.parseInt(port);
if (vncPort != -1) {
vncPort = vncPort - 5900;
} else {
vncPort = null;
}
} catch (final NumberFormatException nfe) {
vncPort = null;
}
}
}
final NodeList rngs = devices.getElementsByTagName("rng");
for (int i = 0; i < rngs.getLength(); i++) {
RngDef def = null;
final Element rng = (Element) rngs.item(i);
final String backendModel = getAttrValue("backend", "model", rng);
final String path = getTagValue("backend", rng);
if (Strings.isNullOrEmpty(backendModel)) {
def = new RngDef(path);
} else {
def = new RngDef(path, RngBackendModel.valueOf(backendModel.toUpperCase()));
}
rngDefs.add(def);
}
final NodeList watchDogs = devices.getElementsByTagName("watchdog");
for (int i = 0; i < watchDogs.getLength(); i++) {
WatchDogDef def = null;
final Element watchDog = (Element) watchDogs.item(i);
final String action = watchDog.getAttribute("action");
final String model = watchDog.getAttribute("model");
if (Strings.isNullOrEmpty(action)) {
def = new WatchDogDef(WatchDogModel.valueOf(model.toUpperCase()));
} else {
def = new WatchDogDef(WatchDogAction.valueOf(action.toUpperCase()), WatchDogModel.valueOf(model.toUpperCase()));
}
watchDogDefs.add(def);
}
return true;
} catch (final ParserConfigurationException e) {
s_logger.debug(e.toString());
} catch (final SAXException e) {
s_logger.debug(e.toString());
} catch (final IOException e) {
s_logger.debug(e.toString());
}
return false;
}
use of com.cloud.hypervisor.kvm.resource.xml.LibvirtDiskDef in project cosmic by MissionCriticalCloud.
the class LibvirtMigrateVolumeCommandWrapper method execute.
@Override
public Answer execute(final MigrateVolumeCommand command, final LibvirtComputingResource libvirtComputingResource) {
String result = null;
final String vmName = command.getAttachedVmName();
LibvirtDiskDef disk = null;
List<LibvirtDiskDef> disks;
Domain dm = null;
Connect conn = null;
String currentVolumePath;
String newVolumePath;
CountDownLatch completeSignal = new CountDownLatch(1);
BlockJobListener blockJobListener = new BlockJobListener() {
@Override
public void onBlockJobCompleted(final Domain domain, final String disk, final int type) throws LibvirtException {
onBlockJobReady(domain, disk, type);
}
@Override
public void onBlockJobFailed(final Domain domain, final String disk, final int type) throws LibvirtException {
throw new LibvirtException("BlockJobFailed");
}
@Override
public void onBlockJobCanceled(final Domain domain, final String disk, final int type) throws LibvirtException {
throw new LibvirtException("BlockJobCanceled");
}
@Override
public void onBlockJobReady(final Domain domain, final String disk, final int type) throws LibvirtException {
domain.blockJobAbort(disk, DomainBlockJobAbortFlags.VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT);
completeSignal.countDown();
}
};
try {
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
disks = libvirtComputingResource.getDisks(conn, vmName);
dm = conn.domainLookupByName(vmName);
newVolumePath = "/mnt/" + command.getPool().getUuid() + "/" + command.getVolumePath();
for (LibvirtDiskDef diskDef : disks) {
if (diskDef.getDiskPath().contains(command.getVolumePath())) {
disk = diskDef;
break;
}
}
logger.debug("Registering block job listener with libvirt for domain " + dm.getName());
dm.addBlockJobListener(blockJobListener);
if (disk != null) {
currentVolumePath = disk.getDiskPath();
disk.setDiskPath(newVolumePath);
logger.debug("Starting block copy for domain " + dm.getName() + " from " + currentVolumePath + " to " + newVolumePath);
dm.blockCopy(currentVolumePath, disk.toString(), new DomainBlockCopyParameters(), 0);
} else {
throw new LibvirtException("Couldn't find disk: " + command.getVolumePath() + " on vm: " + dm.getName());
}
logger.debug("Waiting for block copy for domain " + dm.getName() + " from " + currentVolumePath + " to " + newVolumePath + " to finish");
completeSignal.await();
logger.debug("Refreshing storage pool " + command.getPool().getUuid());
StoragePool storagePool = conn.storagePoolLookupByUUIDString(command.getPool().getUuid());
storagePool.refresh(0);
logger.debug("Cleaning up old disk " + currentVolumePath);
StorageVol storageVol = conn.storageVolLookupByPath(currentVolumePath);
storageVol.delete(0);
} catch (final LibvirtException | InterruptedException e) {
logger.debug("Can't migrate disk: " + e.getMessage());
result = e.getMessage();
} finally {
try {
if (dm != null) {
dm.free();
}
// Stop block job listener
if (conn != null) {
conn.removeBlockJobListener(blockJobListener);
}
} catch (final LibvirtException e) {
logger.debug("Ignoring libvirt error.", e);
}
}
return new MigrateVolumeAnswer(command, result == null, result, command.getVolumePath());
}
Aggregations