protected synchronized String attachOrDetachDisk(Connect conn,
boolean attach, String vmName, KVMPhysicalDisk attachingDisk,
int devId, Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate) throws LibvirtException, InternalErrorException {
List<DiskDef> disks = null;
Domain dm = null;
DiskDef diskdef = null;
KVMStoragePool attachingPool = attachingDisk.getPool();
try {
if (!attach) {
dm = conn.domainLookupByName(vmName);
LibvirtDomainXMLParser parser = new LibvirtDomainXMLParser();
String xml = dm.getXMLDesc(0);
parser.parseDomainXML(xml);
disks = parser.getDisks();
for (DiskDef disk : disks) {
String file = disk.getDiskPath();
if (file != null
&& file.equalsIgnoreCase(attachingDisk.getPath())) {
diskdef = disk;
break;
}
}
if (diskdef == null) {
throw new InternalErrorException("disk: "
+ attachingDisk.getPath()
+ " is not attached before");
}
} else {
diskdef = new DiskDef();
if (attachingPool.getType() == StoragePoolType.RBD) {
diskdef.defNetworkBasedDisk(attachingDisk.getPath(),
attachingPool.getSourceHost(), attachingPool.getSourcePort(),
attachingPool.getAuthUserName(), attachingPool.getUuid(), devId,
DiskDef.diskBus.VIRTIO, diskProtocol.RBD);
} else if (attachingDisk.getFormat() == PhysicalDiskFormat.QCOW2) {
diskdef.defFileBasedDisk(attachingDisk.getPath(), devId,
DiskDef.diskBus.VIRTIO, DiskDef.diskFmtType.QCOW2);
} else if (attachingDisk.getFormat() == PhysicalDiskFormat.RAW) {
diskdef.defBlockBasedDisk(attachingDisk.getPath(), devId,
DiskDef.diskBus.VIRTIO);
}
if ((bytesReadRate != null) && (bytesReadRate > 0))
diskdef.setBytesReadRate(bytesReadRate);
if ((bytesWriteRate != null) && (bytesWriteRate > 0))
diskdef.setBytesWriteRate(bytesWriteRate);
if ((iopsReadRate != null) && (iopsReadRate > 0))
diskdef.setIopsReadRate(iopsReadRate);
if ((iopsWriteRate != null) && (iopsWriteRate > 0))
diskdef.setIopsWriteRate(iopsWriteRate);
}
String xml = diskdef.toString();
return attachOrDetachDevice(conn, attach, vmName, xml);
} finally {
if (dm != null) {
dm.free();
}