use of com.cloud.vm.snapshot.VMSnapshotVO in project cloudstack by apache.
the class UserVmManagerImpl method restoreVMInternal.
public UserVm restoreVMInternal(Account caller, UserVmVO vm, Long newTemplateId) throws InsufficientCapacityException, ResourceUnavailableException {
Long userId = caller.getId();
Account owner = _accountDao.findById(vm.getAccountId());
_userDao.findById(userId);
long vmId = vm.getId();
boolean needRestart = false;
// Input validation
if (owner == null) {
throw new InvalidParameterValueException("The owner of " + vm + " does not exist: " + vm.getAccountId());
}
if (owner.getState() == Account.State.disabled) {
throw new PermissionDeniedException("The owner of " + vm + " is disabled: " + vm.getAccountId());
}
if (vm.getState() != VirtualMachine.State.Running && vm.getState() != VirtualMachine.State.Stopped) {
throw new CloudRuntimeException("Vm " + vm.getUuid() + " currently in " + vm.getState() + " state, restore vm can only execute when VM in Running or Stopped");
}
if (vm.getState() == VirtualMachine.State.Running) {
needRestart = true;
}
List<VolumeVO> rootVols = _volsDao.findByInstanceAndType(vmId, Volume.Type.ROOT);
if (rootVols.isEmpty()) {
InvalidParameterValueException ex = new InvalidParameterValueException("Can not find root volume for VM " + vm.getUuid());
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
if (rootVols.size() > 1) {
InvalidParameterValueException ex = new InvalidParameterValueException("There are " + rootVols.size() + " root volumes for VM " + vm.getUuid());
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
VolumeVO root = rootVols.get(0);
if (!Volume.State.Allocated.equals(root.getState()) || newTemplateId != null) {
Long templateId = root.getTemplateId();
boolean isISO = false;
if (templateId == null) {
// Assuming that for a vm deployed using ISO, template ID is set to NULL
isISO = true;
templateId = vm.getIsoId();
}
// If target VM has associated VM snapshots then don't allow restore of VM
List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vmId);
if (vmSnapshots.size() > 0) {
throw new InvalidParameterValueException("Unable to restore VM, please remove VM snapshots before restoring VM");
}
VMTemplateVO template = null;
//newTemplateId can be either template or ISO id. In the following snippet based on the vm deployment (from template or ISO) it is handled accordingly
if (newTemplateId != null) {
template = _templateDao.findById(newTemplateId);
_accountMgr.checkAccess(caller, null, true, template);
if (isISO) {
if (!template.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Invalid ISO id provided to restore the VM ");
}
} else {
if (template.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Invalid template id provided to restore the VM ");
}
}
} else {
if (isISO && templateId == null) {
throw new CloudRuntimeException("Cannot restore the VM since there is no ISO attached to VM");
}
template = _templateDao.findById(templateId);
if (template == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Cannot find template/ISO for specified volumeid and vmId");
ex.addProxyObject(vm.getUuid(), "vmId");
ex.addProxyObject(root.getUuid(), "volumeId");
throw ex;
}
}
TemplateDataStoreVO tmplStore = _templateStoreDao.findByTemplateZoneReady(template.getId(), vm.getDataCenterId());
if (tmplStore == null) {
throw new InvalidParameterValueException("Cannot restore the vm as the template " + template.getUuid() + " isn't available in the zone");
}
if (needRestart) {
try {
_itMgr.stop(vm.getUuid());
} catch (ResourceUnavailableException e) {
s_logger.debug("Stop vm " + vm.getUuid() + " failed", e);
CloudRuntimeException ex = new CloudRuntimeException("Stop vm failed for specified vmId");
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
}
/* If new template/ISO is provided allocate a new volume from new template/ISO otherwise allocate new volume from original template/ISO */
Volume newVol = null;
if (newTemplateId != null) {
if (isISO) {
newVol = volumeMgr.allocateDuplicateVolume(root, null);
vm.setIsoId(newTemplateId);
vm.setGuestOSId(template.getGuestOSId());
vm.setTemplateId(newTemplateId);
_vmDao.update(vmId, vm);
} else {
newVol = volumeMgr.allocateDuplicateVolume(root, newTemplateId);
vm.setGuestOSId(template.getGuestOSId());
vm.setTemplateId(newTemplateId);
_vmDao.update(vmId, vm);
}
} else {
newVol = volumeMgr.allocateDuplicateVolume(root, null);
}
// 1. Save usage event and update resource count for user vm volumes
_resourceLimitMgr.incrementResourceCount(newVol.getAccountId(), ResourceType.volume, newVol.isDisplay());
_resourceLimitMgr.incrementResourceCount(newVol.getAccountId(), ResourceType.primary_storage, newVol.isDisplay(), new Long(newVol.getSize()));
// 2. Create Usage event for the newly created volume
UsageEventVO usageEvent = new UsageEventVO(EventTypes.EVENT_VOLUME_CREATE, newVol.getAccountId(), newVol.getDataCenterId(), newVol.getId(), newVol.getName(), newVol.getDiskOfferingId(), template.getId(), newVol.getSize());
_usageEventDao.persist(usageEvent);
handleManagedStorage(vm, root);
_volsDao.attachVolume(newVol.getId(), vmId, newVol.getDeviceId());
// Detach, destroy and create the usage event for the old root volume.
_volsDao.detachVolume(root.getId());
volumeMgr.destroyVolume(root);
// For VMware hypervisor since the old root volume is replaced by the new root volume, force expunge old root volume if it has been created in storage
if (vm.getHypervisorType() == HypervisorType.VMware) {
VolumeInfo volumeInStorage = volFactory.getVolume(root.getId());
if (volumeInStorage != null) {
s_logger.info("Expunging volume " + root.getId() + " from primary data store");
AsyncCallFuture<VolumeApiResult> future = _volService.expungeVolumeAsync(volFactory.getVolume(root.getId()));
try {
future.get();
} catch (Exception e) {
s_logger.debug("Failed to expunge volume:" + root.getId(), e);
}
}
}
Map<VirtualMachineProfile.Param, Object> params = null;
String password = null;
if (template.getEnablePassword()) {
password = _mgr.generateRandomPassword();
boolean result = resetVMPasswordInternal(vmId, password);
if (result) {
vm.setPassword(password);
_vmDao.loadDetails(vm);
// update the password in vm_details table too
// Check if an SSH key pair was selected for the instance and if so
// use it to encrypt & save the vm password
encryptAndStorePassword(vm, password);
} else {
throw new CloudRuntimeException("VM reset is completed but failed to reset password for the virtual machine ");
}
}
if (needRestart) {
try {
if (vm.getDetail("password") != null) {
params = new HashMap<VirtualMachineProfile.Param, Object>();
params.put(VirtualMachineProfile.Param.VmPassword, password);
}
_itMgr.start(vm.getUuid(), params);
vm = _vmDao.findById(vmId);
if (template.getEnablePassword()) {
// this value is not being sent to the backend; need only for api
// display purposes
vm.setPassword(password);
if (vm.isUpdateParameters()) {
vm.setUpdateParameters(false);
_vmDao.loadDetails(vm);
if (vm.getDetail("password") != null) {
_vmDetailsDao.remove(_vmDetailsDao.findDetail(vm.getId(), "password").getId());
}
_vmDao.update(vm.getId(), vm);
}
}
} catch (Exception e) {
s_logger.debug("Unable to start VM " + vm.getUuid(), e);
CloudRuntimeException ex = new CloudRuntimeException("Unable to start VM with specified id" + e.getMessage());
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
}
}
s_logger.debug("Restore VM " + vmId + " done successfully");
return vm;
}
use of com.cloud.vm.snapshot.VMSnapshotVO in project cloudstack by apache.
the class VMSnapshotStrategyTest method testRevertSnapshot.
@Test
public void testRevertSnapshot() throws AgentUnavailableException, OperationTimedoutException {
Long hostId = 1L;
Long vmId = 1L;
Long guestOsId = 1L;
HypervisorType hypervisorType = HypervisorType.Any;
String hypervisorVersion = "default";
String guestOsName = "Other";
List<VolumeObjectTO> volumeObjectTOs = new ArrayList<VolumeObjectTO>();
VMSnapshotVO vmSnapshot = Mockito.mock(VMSnapshotVO.class);
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);
GuestOSVO guestOSVO = Mockito.mock(GuestOSVO.class);
Mockito.when(guestOSDao.findById(Matchers.anyLong())).thenReturn(guestOSVO);
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);
VMSnapshotTO vmSnapshotTO = Mockito.mock(VMSnapshotTO.class);
Mockito.when(vmSnapshotHelper.getSnapshotWithParents(Matchers.any(VMSnapshotVO.class))).thenReturn(vmSnapshotTO);
Mockito.when(vmSnapshotDao.findById(Matchers.anyLong())).thenReturn(vmSnapshot);
Mockito.when(vmSnapshot.getId()).thenReturn(1L);
Mockito.when(vmSnapshot.getCreated()).thenReturn(new Date());
Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(null);
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.revertVMSnapshot(vmSnapshot);
} catch (CloudRuntimeException e1) {
e = e1;
}
assertNotNull(e);
RevertToVMSnapshotAnswer answer = Mockito.mock(RevertToVMSnapshotAnswer.class);
Mockito.when(answer.getResult()).thenReturn(Boolean.TRUE);
Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(answer);
boolean result = vmSnapshotStrategy.revertVMSnapshot(vmSnapshot);
assertTrue(result);
}
use of com.cloud.vm.snapshot.VMSnapshotVO in project cloudstack by apache.
the class VMSnapshotStrategyTest method testCreateVMSnapshot.
@Test
public void testCreateVMSnapshot() throws AgentUnavailableException, OperationTimedoutException {
Long hostId = 1L;
Long vmId = 1L;
Long guestOsId = 1L;
HypervisorType hypervisorType = HypervisorType.Any;
String hypervisorVersion = "default";
String guestOsName = "Other";
List<VolumeObjectTO> volumeObjectTOs = new ArrayList<VolumeObjectTO>();
VMSnapshotVO vmSnapshot = Mockito.mock(VMSnapshotVO.class);
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);
GuestOSVO guestOSVO = Mockito.mock(GuestOSVO.class);
Mockito.when(guestOSDao.findById(Matchers.anyLong())).thenReturn(guestOSVO);
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);
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 (CloudRuntimeException e1) {
e = e1;
}
assertNotNull(e);
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.vm.snapshot.VMSnapshotVO in project cloudstack by apache.
the class VMSnapshotStrategyTest method testDeleteVMSnapshot.
@Test
public void testDeleteVMSnapshot() throws AgentUnavailableException, OperationTimedoutException {
Long hostId = 1L;
Long vmId = 1L;
Long guestOsId = 1L;
HypervisorType hypervisorType = HypervisorType.Any;
String hypervisorVersion = "default";
String guestOsName = "Other";
List<VolumeObjectTO> volumeObjectTOs = new ArrayList<VolumeObjectTO>();
VMSnapshotVO vmSnapshot = Mockito.mock(VMSnapshotVO.class);
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);
GuestOSVO guestOSVO = Mockito.mock(GuestOSVO.class);
Mockito.when(guestOSDao.findById(Matchers.anyLong())).thenReturn(guestOSVO);
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);
VMSnapshotTO vmSnapshotTO = Mockito.mock(VMSnapshotTO.class);
Mockito.when(vmSnapshotHelper.getSnapshotWithParents(Matchers.any(VMSnapshotVO.class))).thenReturn(vmSnapshotTO);
Mockito.when(vmSnapshotDao.findById(Matchers.anyLong())).thenReturn(vmSnapshot);
Mockito.when(vmSnapshot.getId()).thenReturn(1L);
Mockito.when(vmSnapshot.getCreated()).thenReturn(new Date());
Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(null);
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.deleteVMSnapshot(vmSnapshot);
} catch (CloudRuntimeException e1) {
e = e1;
}
assertNotNull(e);
DeleteVMSnapshotAnswer answer = Mockito.mock(DeleteVMSnapshotAnswer.class);
Mockito.when(answer.getResult()).thenReturn(true);
Mockito.when(agentMgr.send(Matchers.anyLong(), Matchers.any(Command.class))).thenReturn(answer);
boolean result = vmSnapshotStrategy.deleteVMSnapshot(vmSnapshot);
assertTrue(result);
}
use of com.cloud.vm.snapshot.VMSnapshotVO in project cosmic by MissionCriticalCloud.
the class SnapshotManagerImpl method revertSnapshot.
@Override
public Snapshot revertSnapshot(final Long snapshotId) {
final SnapshotVO snapshot = _snapshotDao.findById(snapshotId);
if (snapshot == null) {
throw new InvalidParameterValueException("No such snapshot");
}
final VolumeVO volume = _volsDao.findById(snapshot.getVolumeId());
if (volume.getState() != Volume.State.Ready) {
throw new InvalidParameterValueException("The volume is not in Ready state.");
}
final Long instanceId = volume.getInstanceId();
// in order to revert the volume
if (instanceId != null) {
final UserVmVO vm = _vmDao.findById(instanceId);
if (vm.getState() != State.Stopped && vm.getState() != State.Shutdowned) {
throw new InvalidParameterValueException("The VM the specified disk is attached to is not in the shutdown state.");
}
// If target VM has associated VM snapshots then don't allow to revert from snapshot
final List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(instanceId);
if (vmSnapshots.size() > 0) {
throw new InvalidParameterValueException("Unable to revert snapshot for VM, please remove VM snapshots before reverting VM from snapshot");
}
}
final SnapshotInfo snapshotInfo = snapshotFactory.getSnapshot(snapshotId, DataStoreRole.Image);
if (snapshotInfo == null) {
throw new CloudRuntimeException("snapshot:" + snapshotId + " not exist in data store");
}
final SnapshotStrategy snapshotStrategy = _storageStrategyFactory.getSnapshotStrategy(snapshot, SnapshotOperation.REVERT);
if (snapshotStrategy == null) {
s_logger.error("Unable to find snaphot strategy to handle snapshot with id '" + snapshotId + "'");
return null;
}
final boolean result = snapshotStrategy.revertSnapshot(snapshotInfo);
if (result) {
// update volume size and primary storage count
_resourceLimitMgr.decrementResourceCount(snapshot.getAccountId(), ResourceType.primary_storage, volume.getSize() - snapshot.getSize());
volume.setSize(snapshot.getSize());
_volsDao.update(volume.getId(), volume);
return snapshotInfo;
}
return null;
}
Aggregations