use of com.xensource.xenapi.Pool in project cosmic by MissionCriticalCloud.
the class XenServerResourceNewBase method initialize.
@Override
public StartupCommand[] initialize() throws IllegalArgumentException {
final StartupCommand[] cmds = super.initialize();
final Connection conn = getConnection();
final Pool pool;
try {
pool = Pool.getByUuid(conn, _host.getPool());
final Pool.Record poolr = pool.getRecord(conn);
final Host.Record masterRecord = poolr.master.getRecord(conn);
if (_host.getUuid().equals(masterRecord.uuid)) {
_listener = new VmEventListener(true);
//
// TODO disable event listener for now. Wait until everything else is ready
//
// _listener.start();
} else {
_listener = new VmEventListener(false);
}
} catch (final XenAPIException e) {
throw new CloudRuntimeException("Unable to determine who is the master", e);
} catch (final XmlRpcException e) {
throw new CloudRuntimeException("Unable to determine who is the master", e);
}
return cmds;
}
use of com.xensource.xenapi.Pool in project cosmic by MissionCriticalCloud.
the class XcpServerDiscoverer method find.
@Override
public Map<? extends ServerResource, Map<String, String>> find(final long dcId, final Long podId, final Long clusterId, final URI url, final String username, final String password, final List<String> hostTags) throws DiscoveryException {
final Map<CitrixResourceBase, Map<String, String>> resources = new HashMap<>();
Connection conn = null;
if (!url.getScheme().equals("http")) {
final String msg = "urlString is not http so we're not taking care of the discovery for this: " + url;
s_logger.debug(msg);
return null;
}
if (clusterId == null) {
final String msg = "must specify cluster Id when add host";
s_logger.debug(msg);
throw new RuntimeException(msg);
}
if (podId == null) {
final String msg = "must specify pod Id when add host";
s_logger.debug(msg);
throw new RuntimeException(msg);
}
final ClusterVO cluster = _clusterDao.findById(clusterId);
if (cluster == null || cluster.getHypervisorType() != HypervisorType.XenServer) {
if (s_logger.isInfoEnabled()) {
s_logger.info("invalid cluster id or cluster is not for XenServer hypervisors");
}
return null;
}
try {
final String hostname = url.getHost();
final InetAddress ia = InetAddress.getByName(hostname);
final String hostIp = ia.getHostAddress();
final Queue<String> pass = new LinkedList<>();
pass.add(password);
conn = _connPool.getConnect(hostIp, username, pass);
if (conn == null) {
final String msg = "Unable to get a connection to " + url;
s_logger.debug(msg);
throw new DiscoveryException(msg);
}
final Set<Pool> pools = Pool.getAll(conn);
final Pool pool = pools.iterator().next();
final Pool.Record pr = pool.getRecord(conn);
String poolUuid = pr.uuid;
final Map<Host, Host.Record> hosts = Host.getAllRecords(conn);
String latestHotFix = "";
if (poolHasHotFix(conn, hostIp, XenserverConfigs.XSHotFix62ESP1004)) {
latestHotFix = XenserverConfigs.XSHotFix62ESP1004;
} else if (poolHasHotFix(conn, hostIp, XenserverConfigs.XSHotFix62ESP1)) {
latestHotFix = XenserverConfigs.XSHotFix62ESP1;
}
/*set cluster hypervisor type to xenserver*/
final ClusterVO clu = _clusterDao.findById(clusterId);
if (clu.getGuid() == null) {
setClusterGuid(clu, poolUuid);
} else {
final List<HostVO> clusterHosts = _resourceMgr.listAllHostsInCluster(clusterId);
if (clusterHosts != null && clusterHosts.size() > 0) {
if (!clu.getGuid().equals(poolUuid)) {
final String msg = "Please join the host " + hostIp + " to XS pool " + clu.getGuid() + " through XC/XS before adding it through CS UI";
s_logger.warn(msg);
throw new DiscoveryException(msg);
}
} else {
setClusterGuid(clu, poolUuid);
}
}
// can not use this conn after this point, because this host may join a pool, this conn is retired
if (conn != null) {
try {
Session.logout(conn);
} catch (final Exception e) {
s_logger.debug("Caught exception during logout", e);
}
conn.dispose();
conn = null;
}
poolUuid = clu.getGuid();
_clusterDao.update(clusterId, clu);
if (_checkHvm) {
for (final Map.Entry<Host, Host.Record> entry : hosts.entrySet()) {
final Host.Record record = entry.getValue();
boolean support_hvm = false;
for (final String capability : record.capabilities) {
if (capability.contains("hvm")) {
support_hvm = true;
break;
}
}
if (!support_hvm) {
final String msg = "Unable to add host " + record.address + " because it doesn't support hvm";
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, msg, msg);
s_logger.debug(msg);
throw new RuntimeException(msg);
}
}
}
for (final Map.Entry<Host, Host.Record> entry : hosts.entrySet()) {
final Host.Record record = entry.getValue();
final String hostAddr = record.address;
final String prodVersion = CitrixHelper.getProductVersion(record);
final String xenVersion = record.softwareVersion.get("xen");
String hostOS = record.softwareVersion.get("product_brand");
if (hostOS == null) {
hostOS = record.softwareVersion.get("platform_name");
}
final String hostOSVer = prodVersion;
final String hostKernelVer = record.softwareVersion.get("linux");
if (_resourceMgr.findHostByGuid(record.uuid) != null) {
s_logger.debug("Skipping " + record.address + " because " + record.uuid + " is already in the database.");
continue;
}
final CitrixResourceBase resource = createServerResource(dcId, podId, record, latestHotFix);
s_logger.info("Found host " + record.hostname + " ip=" + record.address + " product version=" + prodVersion);
final Map<String, String> details = new HashMap<>();
final Map<String, Object> params = new HashMap<>();
details.put("url", hostAddr);
details.put("username", username);
params.put("username", username);
details.put("password", password);
params.put("password", password);
params.put("zone", Long.toString(dcId));
params.put("guid", record.uuid);
params.put("pod", podId.toString());
params.put("cluster", clusterId.toString());
params.put("pool", poolUuid);
params.put("ipaddress", record.address);
details.put(HostInfo.HOST_OS, hostOS);
details.put(HostInfo.HOST_OS_VERSION, hostOSVer);
details.put(HostInfo.HOST_OS_KERNEL_VERSION, hostKernelVer);
details.put(HostInfo.HYPERVISOR_VERSION, xenVersion);
final String privateNetworkLabel = _networkMgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.XenServer);
final String storageNetworkLabel = _networkMgr.getDefaultStorageTrafficLabel(dcId, HypervisorType.XenServer);
if (!params.containsKey("private.network.device") && privateNetworkLabel != null) {
params.put("private.network.device", privateNetworkLabel);
details.put("private.network.device", privateNetworkLabel);
}
if (!params.containsKey("storage.network.device1") && storageNetworkLabel != null) {
params.put("storage.network.device1", storageNetworkLabel);
details.put("storage.network.device1", storageNetworkLabel);
}
params.put("router.aggregation.command.each.timeout", _configDao.getValue(Config.RouterAggregationCommandEachTimeout.toString()));
params.put("wait", Integer.toString(_wait));
details.put("wait", Integer.toString(_wait));
params.put("migratewait", _configDao.getValue(Config.MigrateWait.toString()));
params.put(Config.XenServerMaxNics.toString().toLowerCase(), _configDao.getValue(Config.XenServerMaxNics.toString()));
params.put(Config.XenServerHeartBeatTimeout.toString().toLowerCase(), _configDao.getValue(Config.XenServerHeartBeatTimeout.toString()));
params.put(Config.XenServerHeartBeatInterval.toString().toLowerCase(), _configDao.getValue(Config.XenServerHeartBeatInterval.toString()));
params.put(Config.InstanceName.toString().toLowerCase(), _instance);
details.put(Config.InstanceName.toString().toLowerCase(), _instance);
try {
resource.configure("XenServer", params);
} catch (final ConfigurationException e) {
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + record.address, "Error is " + e.getMessage());
s_logger.warn("Unable to instantiate " + record.address, e);
continue;
}
resource.start();
resources.put(resource, details);
}
} catch (final SessionAuthenticationFailed e) {
throw new DiscoveredWithErrorException("Authentication error");
} catch (final XenAPIException e) {
s_logger.warn("XenAPI exception", e);
return null;
} catch (final XmlRpcException e) {
s_logger.warn("Xml Rpc Exception", e);
return null;
} catch (final UnknownHostException e) {
s_logger.warn("Unable to resolve the host name", e);
return null;
} catch (final Exception e) {
s_logger.debug("other exceptions: " + e.toString(), e);
return null;
}
return resources;
}
use of com.xensource.xenapi.Pool in project cosmic by MissionCriticalCloud.
the class CitrixCreateVMSnapshotCommandWrapper method execute.
@Override
public Answer execute(final CreateVMSnapshotCommand command, final CitrixResourceBase citrixResourceBase) {
final String vmName = command.getVmName();
final String vmSnapshotName = command.getTarget().getSnapshotName();
final List<VolumeObjectTO> listVolumeTo = command.getVolumeTOs();
VmPowerState vmState = VmPowerState.HALTED;
final String guestOSType = command.getGuestOSType();
final String platformEmulator = command.getPlatformEmulator();
final boolean snapshotMemory = command.getTarget().getType() == VMSnapshot.Type.DiskAndMemory;
final long timeout = command.getWait();
final Connection conn = citrixResourceBase.getConnection();
VM vm = null;
VM vmSnapshot = null;
boolean success = false;
try {
// check if VM snapshot already exists
final Set<VM> vmSnapshots = VM.getByNameLabel(conn, command.getTarget().getSnapshotName());
if (vmSnapshots == null || vmSnapshots.size() > 0) {
return new CreateVMSnapshotAnswer(command, command.getTarget(), command.getVolumeTOs());
}
// check if there is already a task for this VM snapshot
Task task = null;
Set<Task> tasks = Task.getByNameLabel(conn, "Async.VM.snapshot");
if (tasks == null) {
tasks = new LinkedHashSet<>();
}
final Set<Task> tasksByName = Task.getByNameLabel(conn, "Async.VM.checkpoint");
if (tasksByName != null) {
tasks.addAll(tasksByName);
}
for (final Task taskItem : tasks) {
if (taskItem.getOtherConfig(conn).containsKey("CS_VM_SNAPSHOT_KEY")) {
final String vmSnapshotTaskName = taskItem.getOtherConfig(conn).get("CS_VM_SNAPSHOT_KEY");
if (vmSnapshotTaskName != null && vmSnapshotTaskName.equals(command.getTarget().getSnapshotName())) {
task = taskItem;
}
}
}
// create a new task if there is no existing task for this VM snapshot
if (task == null) {
try {
vm = citrixResourceBase.getVM(conn, vmName);
vmState = vm.getPowerState(conn);
} catch (final Exception e) {
if (!snapshotMemory) {
vm = citrixResourceBase.createWorkingVM(conn, vmName, guestOSType, platformEmulator, listVolumeTo);
}
}
if (vm == null) {
return new CreateVMSnapshotAnswer(command, false, "Creating VM Snapshot Failed due to can not find vm: " + vmName);
}
// call Xenserver API
if (!snapshotMemory) {
task = vm.snapshotAsync(conn, vmSnapshotName);
} else {
final Set<VBD> vbds = vm.getVBDs(conn);
final Pool pool = Pool.getByUuid(conn, citrixResourceBase.getHost().getPool());
for (final VBD vbd : vbds) {
final VBD.Record vbdr = vbd.getRecord(conn);
if (vbdr.userdevice.equals("0")) {
final VDI vdi = vbdr.VDI;
final SR sr = vdi.getSR(conn);
// store memory image on the same SR with ROOT volume
pool.setSuspendImageSR(conn, sr);
}
}
task = vm.checkpointAsync(conn, vmSnapshotName);
}
task.addToOtherConfig(conn, "CS_VM_SNAPSHOT_KEY", vmSnapshotName);
}
citrixResourceBase.waitForTask(conn, task, 1000, timeout * 1000);
citrixResourceBase.checkForSuccess(conn, task);
final String result = task.getResult(conn);
// extract VM snapshot ref from result
final String ref = result.substring("<value>".length(), result.length() - "</value>".length());
vmSnapshot = Types.toVM(ref);
try {
Thread.sleep(5000);
} catch (final InterruptedException ex) {
}
// calculate used capacity for this VM snapshot
for (final VolumeObjectTO volumeTo : command.getVolumeTOs()) {
final long size = citrixResourceBase.getVMSnapshotChainSize(conn, volumeTo, command.getVmName());
volumeTo.setSize(size);
}
success = true;
return new CreateVMSnapshotAnswer(command, command.getTarget(), command.getVolumeTOs());
} catch (final Exception e) {
String msg = "";
if (e instanceof Types.BadAsyncResult) {
final String licenseKeyWord = "LICENCE_RESTRICTION";
final Types.BadAsyncResult errorResult = (Types.BadAsyncResult) e;
if (errorResult.shortDescription != null && errorResult.shortDescription.contains(licenseKeyWord)) {
msg = licenseKeyWord;
}
} else {
msg = e.toString();
}
s_logger.warn("Creating VM Snapshot " + command.getTarget().getSnapshotName() + " failed due to: " + msg, e);
return new CreateVMSnapshotAnswer(command, false, msg);
} finally {
try {
if (!success) {
if (vmSnapshot != null) {
s_logger.debug("Delete exsisting VM Snapshot " + vmSnapshotName + " after making VolumeTO failed");
final Set<VBD> vbds = vmSnapshot.getVBDs(conn);
for (final VBD vbd : vbds) {
final VBD.Record vbdr = vbd.getRecord(conn);
if (vbdr.type == Types.VbdType.DISK) {
final VDI vdi = vbdr.VDI;
vdi.destroy(conn);
}
}
vmSnapshot.destroy(conn);
}
}
if (vmState == VmPowerState.HALTED) {
if (vm != null) {
vm.destroy(conn);
}
}
} catch (final Exception e2) {
s_logger.error("delete snapshot error due to " + e2.getMessage());
}
}
}
use of com.xensource.xenapi.Pool in project cosmic by MissionCriticalCloud.
the class CitrixClusterVMMetaDataSyncCommandWrapper method execute.
@Override
public Answer execute(final ClusterVMMetaDataSyncCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
// check if this is master
try {
final Pool pool = Pool.getByUuid(conn, citrixResourceBase.getHost().getPool());
final Pool.Record poolr = pool.getRecord(conn);
final Host.Record hostr = poolr.master.getRecord(conn);
if (!citrixResourceBase.getHost().getUuid().equals(hostr.uuid)) {
return new ClusterVMMetaDataSyncAnswer(command.getClusterId(), null);
}
} catch (XmlRpcException | XenAPIException e) {
s_logger.warn("Check for master failed, failing the Cluster sync VMMetaData command");
return new ClusterVMMetaDataSyncAnswer(command.getClusterId(), null);
}
final HashMap<String, String> vmMetadatum = citrixResourceBase.clusterVMMetaDataSync(conn);
return new ClusterVMMetaDataSyncAnswer(command.getClusterId(), vmMetadatum);
}
use of com.xensource.xenapi.Pool in project cosmic by MissionCriticalCloud.
the class NotAValidCommand method testClusterVMMetaDataSyncCommand.
@Test
public void testClusterVMMetaDataSyncCommand() {
final String uuid = "6172d8b7-ba10-4a70-93f9-ecaf41f51d53";
final Connection conn = Mockito.mock(Connection.class);
final XsHost xsHost = Mockito.mock(XsHost.class);
final Pool pool = PowerMockito.mock(Pool.class);
final Pool.Record poolr = Mockito.mock(Pool.Record.class);
final Host.Record hostr = Mockito.mock(Host.Record.class);
final Host master = Mockito.mock(Host.class);
final ClusterVMMetaDataSyncCommand vmDataSync = new ClusterVMMetaDataSyncCommand(10, 1l);
final CitrixRequestWrapper wrapper = CitrixRequestWrapper.getInstance();
assertNotNull(wrapper);
when(citrixResourceBase.getConnection()).thenReturn(conn);
try {
when(citrixResourceBase.getHost()).thenReturn(xsHost);
when(citrixResourceBase.getHost().getUuid()).thenReturn(uuid);
when(xsHost.getPool()).thenReturn("pool");
PowerMockito.mockStatic(Pool.class);
when(Pool.getByUuid(conn, "pool")).thenReturn(pool);
PowerMockito.mockStatic(Pool.Record.class);
when(pool.getRecord(conn)).thenReturn(poolr);
poolr.master = master;
when(poolr.master.getRecord(conn)).thenReturn(hostr);
hostr.uuid = uuid;
} catch (final XenAPIException | XmlRpcException e) {
fail(e.getMessage());
}
final Answer answer = wrapper.execute(vmDataSync, citrixResourceBase);
verify(citrixResourceBase, times(1)).getConnection();
assertTrue(answer.getResult());
}
Aggregations