use of com.xensource.xenapi.Connection in project cloudstack by apache.
the class XenServer610MigrateWithStorageCompleteCommandWrapper method execute.
@Override
public Answer execute(final MigrateWithStorageCompleteCommand command, final XenServer610Resource xenServer610Resource) {
final Connection connection = xenServer610Resource.getConnection();
final VirtualMachineTO vmSpec = command.getVirtualMachine();
final String name = vmSpec.getName();
try {
final XsHost xsHost = xenServer610Resource.getHost();
final String uuid = xsHost.getUuid();
final Set<VM> vms = VM.getByNameLabel(connection, name);
// Check if VMs can be found by label.
if (vms == null) {
throw new CloudRuntimeException("Couldn't find VMs by label " + name + " on the destination host.");
}
final VM migratedVm = vms.iterator().next();
// Check the vm is present on the new host.
if (migratedVm == null) {
throw new CloudRuntimeException("Couldn't find the migrated vm " + name + " on the destination host.");
}
final Host host = Host.getByUuid(connection, uuid);
migratedVm.setAffinity(connection, host);
// Volume paths would have changed. Return that information.
final List<VolumeObjectTO> volumeToSet = xenServer610Resource.getUpdatedVolumePathsOfMigratedVm(connection, migratedVm, vmSpec.getDisks());
return new MigrateWithStorageCompleteAnswer(command, volumeToSet);
} catch (final CloudRuntimeException e) {
s_logger.error("Migration of vm " + name + " with storage failed due to " + e.toString(), e);
return new MigrateWithStorageCompleteAnswer(command, e);
} catch (final Exception e) {
s_logger.error("Migration of vm " + name + " with storage failed due to " + e.toString(), e);
return new MigrateWithStorageCompleteAnswer(command, e);
}
}
use of com.xensource.xenapi.Connection in project cloudstack by apache.
the class CitrixCreateStoragePoolCommandWrapper method execute.
@Override
public Answer execute(final CreateStoragePoolCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final StorageFilerTO pool = command.getPool();
try {
if (command.getCreateDatastore()) {
Map<String, String> details = command.getDetails();
String srNameLabel = details.get(CreateStoragePoolCommand.DATASTORE_NAME);
String storageHost = details.get(CreateStoragePoolCommand.STORAGE_HOST);
String iqn = details.get(CreateStoragePoolCommand.IQN);
citrixResourceBase.getIscsiSR(conn, srNameLabel, storageHost, iqn, null, null, false);
} else {
if (pool.getType() == StoragePoolType.NetworkFilesystem) {
citrixResourceBase.getNfsSR(conn, Long.toString(pool.getId()), pool.getUuid(), pool.getHost(), pool.getPath(), pool.toString());
} else if (pool.getType() == StoragePoolType.IscsiLUN) {
citrixResourceBase.getIscsiSR(conn, pool.getUuid(), pool.getHost(), pool.getPath(), null, null, false);
} else if (pool.getType() == StoragePoolType.PreSetup) {
} else {
return new Answer(command, false, "The pool type: " + pool.getType().name() + " is not supported.");
}
}
return new Answer(command, true, "success");
} catch (final Exception e) {
final String msg = "Catch Exception " + e.getClass().getName() + ", create StoragePool failed due to " + e.toString() + " on host:" + citrixResourceBase.getHost().getUuid() + " pool: " + pool.getHost() + pool.getPath();
s_logger.warn(msg, e);
return new Answer(command, false, msg);
}
}
use of com.xensource.xenapi.Connection in project cloudstack by apache.
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.Connection in project cloudstack by apache.
the class CitrixDeleteVMSnapshotCommandWrapper method execute.
@Override
public Answer execute(final DeleteVMSnapshotCommand command, final CitrixResourceBase citrixResourceBase) {
final String snapshotName = command.getTarget().getSnapshotName();
final Connection conn = citrixResourceBase.getConnection();
try {
final List<VDI> vdiList = new ArrayList<VDI>();
final Set<VM> snapshots = VM.getByNameLabel(conn, snapshotName);
if (snapshots == null || snapshots.size() == 0) {
s_logger.warn("VM snapshot with name " + snapshotName + " does not exist, assume it is already deleted");
return new DeleteVMSnapshotAnswer(command, command.getVolumeTOs());
}
final VM snapshot = snapshots.iterator().next();
final Set<VBD> vbds = snapshot.getVBDs(conn);
for (final VBD vbd : vbds) {
if (vbd.getType(conn) == Types.VbdType.DISK) {
final VDI vdi = vbd.getVDI(conn);
vdiList.add(vdi);
}
}
if (command.getTarget().getType() == VMSnapshot.Type.DiskAndMemory) {
vdiList.add(snapshot.getSuspendVDI(conn));
}
snapshot.destroy(conn);
for (final VDI vdi : vdiList) {
vdi.destroy(conn);
}
try {
Thread.sleep(5000);
} catch (final InterruptedException ex) {
}
// re-calculate used capacify for this VM snapshot
for (final VolumeObjectTO volumeTo : command.getVolumeTOs()) {
final long size = citrixResourceBase.getVMSnapshotChainSize(conn, volumeTo, command.getVmName());
volumeTo.setSize(size);
}
return new DeleteVMSnapshotAnswer(command, command.getVolumeTOs());
} catch (final Exception e) {
s_logger.warn("Catch Exception: " + e.getClass().toString() + " due to " + e.toString(), e);
return new DeleteVMSnapshotAnswer(command, false, e.getMessage());
}
}
use of com.xensource.xenapi.Connection in project cloudstack by apache.
the class Xenserver625StorageProcessor method backupSnapshot.
@Override
public Answer backupSnapshot(final CopyCommand cmd) {
final Connection conn = hypervisorResource.getConnection();
final DataTO srcData = cmd.getSrcTO();
final DataTO cacheData = cmd.getCacheTO();
final DataTO destData = cmd.getDestTO();
final int wait = cmd.getWait();
final PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO) srcData.getDataStore();
final String primaryStorageNameLabel = primaryStore.getUuid();
String secondaryStorageUrl = null;
NfsTO cacheStore = null;
String destPath = null;
if (cacheData != null) {
cacheStore = (NfsTO) cacheData.getDataStore();
secondaryStorageUrl = cacheStore.getUrl();
destPath = cacheData.getPath();
} else {
cacheStore = (NfsTO) destData.getDataStore();
secondaryStorageUrl = cacheStore.getUrl();
destPath = destData.getPath();
}
final SnapshotObjectTO snapshotTO = (SnapshotObjectTO) srcData;
final SnapshotObjectTO snapshotOnImage = (SnapshotObjectTO) destData;
String snapshotUuid = snapshotTO.getPath();
final String prevBackupUuid = snapshotOnImage.getParentSnapshotPath();
final String prevSnapshotUuid = snapshotTO.getParentSnapshotPath();
final Map<String, String> options = cmd.getOptions();
// By default assume failure
String details = null;
String snapshotBackupUuid = null;
boolean fullbackup = Boolean.parseBoolean(options.get("fullSnapshot"));
Long physicalSize = null;
try {
SR primaryStorageSR = null;
if (primaryStore.isManaged()) {
// currently, managed storage only supports full backup
fullbackup = true;
final Map<String, String> srcDetails = cmd.getOptions();
final String iScsiName = srcDetails.get(DiskTO.IQN);
final String storageHost = srcDetails.get(DiskTO.STORAGE_HOST);
final String chapInitiatorUsername = srcDetails.get(DiskTO.CHAP_INITIATOR_USERNAME);
final String chapInitiatorSecret = srcDetails.get(DiskTO.CHAP_INITIATOR_SECRET);
final String srType = CitrixResourceBase.SRType.LVMOISCSI.toString();
primaryStorageSR = hypervisorResource.getIscsiSR(conn, iScsiName, storageHost, iScsiName, chapInitiatorUsername, chapInitiatorSecret, false, srType, true);
final VDI srcVdi = primaryStorageSR.getVDIs(conn).iterator().next();
if (srcVdi == null) {
throw new InternalErrorException("Could not Find a VDI on the SR: " + primaryStorageSR.getNameLabel(conn));
}
snapshotUuid = srcVdi.getUuid(conn);
} else {
primaryStorageSR = hypervisorResource.getSRByNameLabelandHost(conn, primaryStorageNameLabel);
}
if (primaryStorageSR == null) {
throw new InternalErrorException("Could not backup snapshot because the primary Storage SR could not be created from the name label: " + primaryStorageNameLabel);
}
// String psUuid = primaryStorageSR.getUuid(conn);
final Boolean isISCSI = IsISCSI(primaryStorageSR.getType(conn));
final VDI snapshotVdi = getVDIbyUuid(conn, snapshotUuid);
final String snapshotPaUuid = snapshotVdi.getUuid(conn);
final URI uri = new URI(secondaryStorageUrl);
final String secondaryStorageMountPath = uri.getHost() + ":" + uri.getPath();
final DataStoreTO destStore = destData.getDataStore();
final String folder = destPath;
String finalPath = null;
final String localMountPoint = BaseMountPointOnHost + File.separator + UUID.nameUUIDFromBytes(secondaryStorageUrl.getBytes()).toString();
if (fullbackup) {
SR snapshotSr = null;
Task task = null;
try {
final String localDir = "/var/cloud_mount/" + UUID.nameUUIDFromBytes(secondaryStorageMountPath.getBytes());
mountNfs(conn, secondaryStorageMountPath, localDir);
final boolean result = makeDirectory(conn, localDir + "/" + folder);
if (!result) {
details = " Filed to create folder " + folder + " in secondary storage";
s_logger.warn(details);
return new CopyCmdAnswer(details);
}
snapshotSr = createFileSr(conn, secondaryStorageMountPath, folder);
task = snapshotVdi.copyAsync(conn, snapshotSr, null, null);
// poll every 1 seconds ,
hypervisorResource.waitForTask(conn, task, 1000, wait * 1000);
hypervisorResource.checkForSuccess(conn, task);
final VDI backedVdi = Types.toVDI(task, conn);
snapshotBackupUuid = backedVdi.getUuid(conn);
physicalSize = backedVdi.getPhysicalUtilisation(conn);
if (destStore instanceof SwiftTO) {
try {
final String container = "S-" + snapshotTO.getVolume().getVolumeId().toString();
final String destSnapshotName = swiftBackupSnapshot(conn, (SwiftTO) destStore, snapshotSr.getUuid(conn), snapshotBackupUuid, container, false, wait);
final String swiftPath = container + File.separator + destSnapshotName;
finalPath = swiftPath;
} finally {
try {
deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid);
} catch (final Exception e) {
s_logger.debug("Failed to delete snapshot on cache storages", e);
}
}
} else if (destStore instanceof S3TO) {
try {
finalPath = backupSnapshotToS3(conn, (S3TO) destStore, snapshotSr.getUuid(conn), folder, snapshotBackupUuid, isISCSI, wait);
if (finalPath == null) {
throw new CloudRuntimeException("S3 upload of snapshots " + snapshotBackupUuid + " failed");
}
} finally {
try {
deleteSnapshotBackup(conn, localMountPoint, folder, secondaryStorageMountPath, snapshotBackupUuid);
} catch (final Exception e) {
s_logger.debug("Failed to delete snapshot on cache storages", e);
}
}
// finalPath = folder + File.separator +
// snapshotBackupUuid;
} else {
finalPath = folder + File.separator + snapshotBackupUuid + ".vhd";
}
} finally {
if (task != null) {
try {
task.destroy(conn);
} catch (final Exception e) {
s_logger.warn("unable to destroy task(" + task.toWireString() + ") due to " + e.toString());
}
}
if (snapshotSr != null) {
hypervisorResource.removeSR(conn, snapshotSr);
}
if (primaryStore.isManaged()) {
hypervisorResource.removeSR(conn, primaryStorageSR);
}
}
} else {
final String primaryStorageSRUuid = primaryStorageSR.getUuid(conn);
if (destStore instanceof SwiftTO) {
final String container = "S-" + snapshotTO.getVolume().getVolumeId().toString();
snapshotBackupUuid = swiftBackupSnapshot(conn, (SwiftTO) destStore, primaryStorageSRUuid, snapshotPaUuid, "S-" + snapshotTO.getVolume().getVolumeId().toString(), isISCSI, wait);
finalPath = container + File.separator + snapshotBackupUuid;
} else if (destStore instanceof S3TO) {
finalPath = backupSnapshotToS3(conn, (S3TO) destStore, primaryStorageSRUuid, folder, snapshotPaUuid, isISCSI, wait);
if (finalPath == null) {
throw new CloudRuntimeException("S3 upload of snapshots " + snapshotPaUuid + " failed");
}
} else {
final String result = backupSnapshot(conn, primaryStorageSRUuid, localMountPoint, folder, secondaryStorageMountPath, snapshotUuid, prevBackupUuid, prevSnapshotUuid, isISCSI, wait);
final String[] tmp = result.split("#");
snapshotBackupUuid = tmp[0];
physicalSize = Long.parseLong(tmp[1]);
finalPath = folder + File.separator + snapshotBackupUuid + ".vhd";
}
final String volumeUuid = snapshotTO.getVolume().getPath();
destroySnapshotOnPrimaryStorageExceptThis(conn, volumeUuid, snapshotUuid);
}
final SnapshotObjectTO newSnapshot = new SnapshotObjectTO();
newSnapshot.setPath(finalPath);
newSnapshot.setPhysicalSize(physicalSize);
if (fullbackup) {
newSnapshot.setParentSnapshotPath(null);
} else {
newSnapshot.setParentSnapshotPath(prevBackupUuid);
}
return new CopyCmdAnswer(newSnapshot);
} catch (final Types.XenAPIException e) {
details = "BackupSnapshot Failed due to " + e.toString();
s_logger.warn(details, e);
} catch (final Exception e) {
details = "BackupSnapshot Failed due to " + e.getMessage();
s_logger.warn(details, e);
}
return new CopyCmdAnswer(details);
}
Aggregations