public class LibvirtUtil {
private Connect conn;
private static Logger LOG = Logger.getLogger(LibvirtUtil.class.getName());
public void connect() {
if (conn == null) {
ConnectAuth ca = new ConnectAuthDefault();
try {
conn = new Connect("qemu:///system", ca, 0);
} catch (LibvirtException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
}
public void disconnect() {
if (conn != null) {
try {
conn.close();
conn = null;
} catch (LibvirtException ex) {
LOG.log(Level.SEVERE, null, ex);
}
}
}
public VmModel[] getVmList() {
VmModel[] ret = null;
try {
NodeInfo ni = conn.nodeInfo();
LOG.log(Level.INFO, "model: " + ni.model + " mem(kb):" + ni.memory);
int numOfVMs = conn.numOfDomains();
LOG.log(Level.INFO, String.format("Total %d VMs", numOfVMs));
ret = new VmModel[numOfVMs];
int[] domains = conn.listDomains();
for (int i = 0; i < numOfVMs; i++) {
ret[i] = new VmModel();
Domain vm = conn.domainLookupByID(domains[i]);
LOG.log(Level.INFO, "vm name: " + vm.getName() + " type: " + vm.getOSType()
+ " max mem: " + vm.getMaxMemory() + " max cpu: " + vm.getMaxVcpus());
ret[i].setCpu(vm.getMaxVcpus());
ret[i].setMem(vm.getMaxMemory());
ret[i].setName(vm.getName());
ret[i].setUuid(vm.getUUIDString());
}
} catch (LibvirtException ex) {
LOG.log(Level.SEVERE, null, ex);
return null;
}
return ret;
}
}