private synchronized IConnect getOrCreateConnection() throws VirtException {
if (connection == null || !connection.isConnected()) {
ConnectionBuilder builder = createBuilder();
LOGGER.log(Level.INFO, "Trying to establish a connection to hypervisor URI: {0} as {1}/******",
new Object[]{builder.constructHypervisorURI(), username});
try {
connection = builder.build();
LOGGER.log(Level.INFO, "Established connection to hypervisor URI: {0} as {1}/******",
new Object[]{builder.constructHypervisorURI(), username});
} catch (VirtException e) {
LogRecord rec = new LogRecord(Level.SEVERE, "Failed to establish connection to hypervisor URI: {0} as {1}/******");
rec.setThrown(e);
rec.setParameters(new Object[]{builder.constructHypervisorURI(), username});
LOGGER.log(rec);
}
} else {
try {
// the connection appears to be up but might actually be dead (e.g. due to a restart of libvirtd)
// lets try a simple function call and see if it turns out ok
connection.getVersion();
} catch (VirtException lve) {
ConnectionBuilder builder = createBuilder();
LogRecord rec = new LogRecord(Level.WARNING, "Connection appears to be broken, trying to reconnect: {0} as {1}/******");
rec.setParameters(new Object[]{builder.constructHypervisorURI(), username});
LOGGER.log(rec);
try {
connection = builder.build();
} catch (VirtException lve2) {
rec = new LogRecord(Level.SEVERE, "Failed to re-establish connection to hypervisor URI: {0} as {1}/******");
rec.setThrown(lve2);
rec.setParameters(new Object[]{builder.constructHypervisorURI(), username});
LOGGER.log(rec);
}
}
}
return connection;