Search in sources :

Example 1 with VMSnapshotVO

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;
}
Also used : Account(com.cloud.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) UsageEventVO(com.cloud.event.UsageEventVO) VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) VolumeApiResult(org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) TemplateDataStoreVO(org.apache.cloudstack.storage.datastore.db.TemplateDataStoreVO) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) CloudException(com.cloud.exception.CloudException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) Volume(com.cloud.storage.Volume) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 2 with VMSnapshotVO

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);
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) RevertToVMSnapshotAnswer(com.cloud.agent.api.RevertToVMSnapshotAnswer) ArrayList(java.util.ArrayList) GuestOSVO(com.cloud.storage.GuestOSVO) Date(java.util.Date) HostVO(com.cloud.host.HostVO) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) GuestOSHypervisorVO(com.cloud.storage.GuestOSHypervisorVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) VMSnapshotTO(com.cloud.agent.api.VMSnapshotTO) Command(com.cloud.agent.api.Command) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) Test(org.junit.Test)

Example 3 with VMSnapshotVO

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);
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) ArrayList(java.util.ArrayList) GuestOSVO(com.cloud.storage.GuestOSVO) VMSnapshot(com.cloud.vm.snapshot.VMSnapshot) HostVO(com.cloud.host.HostVO) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) GuestOSHypervisorVO(com.cloud.storage.GuestOSHypervisorVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) CreateVMSnapshotAnswer(com.cloud.agent.api.CreateVMSnapshotAnswer) Command(com.cloud.agent.api.Command) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) Test(org.junit.Test)

Example 4 with VMSnapshotVO

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);
}
Also used : UserVmVO(com.cloud.vm.UserVmVO) ArrayList(java.util.ArrayList) GuestOSVO(com.cloud.storage.GuestOSVO) Date(java.util.Date) HostVO(com.cloud.host.HostVO) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IOException(java.io.IOException) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) GuestOSHypervisorVO(com.cloud.storage.GuestOSHypervisorVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) VMSnapshotTO(com.cloud.agent.api.VMSnapshotTO) Command(com.cloud.agent.api.Command) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) VolumeObjectTO(org.apache.cloudstack.storage.to.VolumeObjectTO) DeleteVMSnapshotAnswer(com.cloud.agent.api.DeleteVMSnapshotAnswer) Test(org.junit.Test)

Example 5 with VMSnapshotVO

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;
}
Also used : VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) UserVmVO(com.cloud.vm.UserVmVO) SnapshotInfo(com.cloud.engine.subsystem.api.storage.SnapshotInfo) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SnapshotStrategy(com.cloud.engine.subsystem.api.storage.SnapshotStrategy)

Aggregations

VMSnapshotVO (com.cloud.vm.snapshot.VMSnapshotVO)58 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)35 UserVmVO (com.cloud.vm.UserVmVO)27 AgentUnavailableException (com.cloud.exception.AgentUnavailableException)20 OperationTimedoutException (com.cloud.exception.OperationTimedoutException)20 Account (com.cloud.user.Account)17 HostVO (com.cloud.host.HostVO)16 VMSnapshotTO (com.cloud.agent.api.VMSnapshotTO)15 GuestOSVO (com.cloud.storage.GuestOSVO)15 Test (org.junit.Test)14 HypervisorType (com.cloud.hypervisor.Hypervisor.HypervisorType)13 GuestOSHypervisorVO (com.cloud.storage.GuestOSHypervisorVO)13 NoTransitionException (com.cloud.utils.fsm.NoTransitionException)13 ArrayList (java.util.ArrayList)13 VolumeObjectTO (org.apache.cloudstack.storage.to.VolumeObjectTO)12 VolumeVO (com.cloud.storage.VolumeVO)11 ConfigurationException (javax.naming.ConfigurationException)11 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)10 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)10 IOException (java.io.IOException)10