use of com.cloud.legacymodel.communication.answer.CreateVMSnapshotAnswer in project cosmic by MissionCriticalCloud.
the class DefaultVMSnapshotStrategy method processAnswer.
@DB
protected void processAnswer(final VMSnapshotVO vmSnapshot, final UserVm userVm, final Answer as, final Long hostId) {
try {
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<NoTransitionException>() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) throws NoTransitionException {
if (as instanceof CreateVMSnapshotAnswer) {
final CreateVMSnapshotAnswer answer = (CreateVMSnapshotAnswer) as;
finalizeCreate(vmSnapshot, answer.getVolumeTOs());
vmSnapshotHelper.vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationSucceeded);
} else if (as instanceof RevertToVMSnapshotAnswer) {
final RevertToVMSnapshotAnswer answer = (RevertToVMSnapshotAnswer) as;
finalizeRevert(vmSnapshot, answer.getVolumeTOs());
vmSnapshotHelper.vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationSucceeded);
} else if (as instanceof DeleteVMSnapshotAnswer) {
final DeleteVMSnapshotAnswer answer = (DeleteVMSnapshotAnswer) as;
finalizeDelete(vmSnapshot, answer.getVolumeTOs());
vmSnapshotDao.remove(vmSnapshot.getId());
}
}
});
} catch (final Exception e) {
final String errMsg = "Error while process answer: " + as.getClass() + " due to " + e.getMessage();
s_logger.error(errMsg, e);
throw new CloudRuntimeException(errMsg);
}
}
use of com.cloud.legacymodel.communication.answer.CreateVMSnapshotAnswer 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.cloud.legacymodel.communication.answer.CreateVMSnapshotAnswer in project cosmic by MissionCriticalCloud.
the class LibvirtCreateVMSnapshotCommandWrapper method execute.
@Override
public Answer execute(final CreateVMSnapshotCommand cmd, final LibvirtComputingResource libvirtComputingResource) {
final String vmName = cmd.getVmName();
final String vmSnapshotName = cmd.getTarget().getSnapshotName();
Domain dm = null;
try {
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
final Connect conn = libvirtUtilitiesHelper.getConnection();
dm = libvirtComputingResource.getDomain(conn, vmName);
if (dm == null) {
return new CreateVMSnapshotAnswer(cmd, false, "Create VM Snapshot Failed due to can not find vm: " + vmName);
}
final DomainState domainState = dm.getInfo().state;
if (domainState != DomainState.VIR_DOMAIN_RUNNING) {
return new CreateVMSnapshotAnswer(cmd, false, "Create VM Snapshot Failed due to vm is not running: " + vmName + " with domainState = " + domainState);
}
final String vmSnapshotXML = "<domainsnapshot><name>" + vmSnapshotName + "</name><memory snapshot='internal' /></domainsnapshot>";
dm.snapshotCreateXML(vmSnapshotXML);
return new CreateVMSnapshotAnswer(cmd, cmd.getTarget(), cmd.getVolumeTOs());
} catch (final LibvirtException e) {
final String msg = " Create VM snapshot failed due to " + e.toString();
s_logger.warn(msg, e);
return new CreateVMSnapshotAnswer(cmd, false, msg);
} finally {
if (dm != null) {
try {
dm.free();
} catch (final LibvirtException l) {
s_logger.trace("Ignoring libvirt error.", l);
}
}
}
}
use of com.cloud.legacymodel.communication.answer.CreateVMSnapshotAnswer in project cosmic by MissionCriticalCloud.
the class VMSnapshotStrategyTest method testCreateVMSnapshot.
@Test
public void testCreateVMSnapshot() throws AgentUnavailableException, OperationTimedoutException {
final Long hostId = 1L;
final Long vmId = 1L;
final Long guestOsId = 1L;
final HypervisorType hypervisorType = HypervisorType.Any;
final String hypervisorVersion = "default";
final String guestOsName = "Other";
final List<VolumeObjectTO> volumeObjectTOs = new ArrayList<>();
final VMSnapshotVO vmSnapshot = Mockito.mock(VMSnapshotVO.class);
final UserVmVO userVmVO = Mockito.mock(UserVmVO.class);
Mockito.when(userVmVO.getGuestOSId()).thenReturn(guestOsId);
Mockito.when(vmSnapshot.getVmId()).thenReturn(vmId);
Mockito.when(vmSnapshotHelper.pickRunningHost(Matchers.anyLong())).thenReturn(hostId);
Mockito.when(vmSnapshotHelper.getVolumeTOList(Matchers.anyLong())).thenReturn(volumeObjectTOs);
Mockito.when(userVmDao.findById(Matchers.anyLong())).thenReturn(userVmVO);
final GuestOSVO guestOSVO = Mockito.mock(GuestOSVO.class);
Mockito.when(guestOSDao.findById(Matchers.anyLong())).thenReturn(guestOSVO);
final GuestOSHypervisorVO guestOSHypervisorVO = Mockito.mock(GuestOSHypervisorVO.class);
Mockito.when(guestOSHypervisorVO.getGuestOsName()).thenReturn(guestOsName);
Mockito.when(guestOsHypervisorDao.findById(Matchers.anyLong())).thenReturn(guestOSHypervisorVO);
Mockito.when(guestOsHypervisorDao.findByOsIdAndHypervisor(Matchers.anyLong(), Matchers.anyString(), Matchers.anyString())).thenReturn(guestOSHypervisorVO);
Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(null);
final HostVO hostVO = Mockito.mock(HostVO.class);
Mockito.when(hostDao.findById(Matchers.anyLong())).thenReturn(hostVO);
Mockito.when(hostVO.getHypervisorType()).thenReturn(hypervisorType);
Mockito.when(hostVO.getHypervisorVersion()).thenReturn(hypervisorVersion);
Exception e = null;
try {
vmSnapshotStrategy.takeVMSnapshot(vmSnapshot);
} catch (final CloudRuntimeException e1) {
e = e1;
}
assertNotNull(e);
final CreateVMSnapshotAnswer answer = Mockito.mock(CreateVMSnapshotAnswer.class);
Mockito.when(answer.getResult()).thenReturn(true);
Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(answer);
Mockito.when(vmSnapshotDao.findById(Matchers.anyLong())).thenReturn(vmSnapshot);
VMSnapshot snapshot = null;
snapshot = vmSnapshotStrategy.takeVMSnapshot(vmSnapshot);
assertNotNull(snapshot);
}
use of com.cloud.legacymodel.communication.answer.CreateVMSnapshotAnswer in project cosmic by MissionCriticalCloud.
the class DefaultVMSnapshotStrategy method takeVMSnapshot.
@Override
public VMSnapshot takeVMSnapshot(final VMSnapshot vmSnapshot) {
final Long hostId = vmSnapshotHelper.pickRunningHost(vmSnapshot.getVmId());
final UserVm userVm = userVmDao.findById(vmSnapshot.getVmId());
final VMSnapshotVO vmSnapshotVO = (VMSnapshotVO) vmSnapshot;
try {
vmSnapshotHelper.vmSnapshotStateTransitTo(vmSnapshotVO, VMSnapshot.Event.CreateRequested);
} catch (final NoTransitionException e) {
throw new CloudRuntimeException(e.getMessage());
}
CreateVMSnapshotAnswer answer = null;
boolean result = false;
try {
final GuestOSVO guestOS = guestOSDao.findById(userVm.getGuestOSId());
final List<VolumeObjectTO> volumeTOs = vmSnapshotHelper.getVolumeTOList(userVm.getId());
VMSnapshotTO current = null;
final VMSnapshotVO currentSnapshot = vmSnapshotDao.findCurrentSnapshotByVmId(userVm.getId());
if (currentSnapshot != null) {
current = vmSnapshotHelper.getSnapshotWithParents(currentSnapshot);
}
final VMSnapshotOptions options = ((VMSnapshotVO) vmSnapshot).getOptions();
boolean quiescevm = true;
if (options != null) {
quiescevm = options.needQuiesceVM();
}
final VMSnapshotTO target = new VMSnapshotTO(vmSnapshot.getId(), vmSnapshot.getName(), vmSnapshot.getType(), null, vmSnapshot.getDescription(), false, current, quiescevm);
if (current == null) {
vmSnapshotVO.setParent(null);
} else {
vmSnapshotVO.setParent(current.getId());
}
final HostVO host = hostDao.findById(hostId);
final GuestOSHypervisorVO guestOsMapping = guestOsHypervisorDao.findByOsIdAndHypervisor(guestOS.getId(), host.getHypervisorType().toString(), host.getHypervisorVersion());
final CreateVMSnapshotCommand ccmd = new CreateVMSnapshotCommand(userVm.getInstanceName(), userVm.getUuid(), target, volumeTOs, guestOS.getDisplayName());
if (guestOsMapping == null) {
ccmd.setPlatformEmulator(null);
} else {
ccmd.setPlatformEmulator(guestOsMapping.getGuestOsName());
}
ccmd.setWait(_wait);
answer = (CreateVMSnapshotAnswer) agentMgr.send(hostId, ccmd);
if (answer != null && answer.getResult()) {
processAnswer(vmSnapshotVO, userVm, answer, hostId);
s_logger.debug("Create vm snapshot " + vmSnapshot.getName() + " succeeded for vm: " + userVm.getInstanceName());
result = true;
return vmSnapshot;
} else {
String errMsg = "Creating VM snapshot: " + vmSnapshot.getName() + " failed";
if (answer != null && answer.getDetails() != null) {
errMsg = errMsg + " due to " + answer.getDetails();
}
s_logger.error(errMsg);
throw new CloudRuntimeException(errMsg);
}
} catch (final OperationTimedoutException e) {
s_logger.debug("Creating VM snapshot: " + vmSnapshot.getName() + " failed: " + e.toString());
throw new CloudRuntimeException("Creating VM snapshot: " + vmSnapshot.getName() + " failed: " + e.toString());
} catch (final AgentUnavailableException e) {
s_logger.debug("Creating VM snapshot: " + vmSnapshot.getName() + " failed", e);
throw new CloudRuntimeException("Creating VM snapshot: " + vmSnapshot.getName() + " failed: " + e.toString());
} finally {
if (!result) {
try {
vmSnapshotHelper.vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationFailed);
} catch (final NoTransitionException e1) {
s_logger.error("Cannot set vm snapshot state due to: " + e1.getMessage());
}
}
}
}
Aggregations