Search in sources :

Example 21 with VMSnapshotVO

use of com.cloud.vm.snapshot.VMSnapshotVO in project cloudstack by apache.

the class VolumeApiServiceImpl method attachVolumeToVM.

public Volume attachVolumeToVM(Long vmId, Long volumeId, Long deviceId) {
    Account caller = CallContext.current().getCallingAccount();
    // Check that the volume ID is valid
    VolumeInfo volumeToAttach = volFactory.getVolume(volumeId);
    // Check that the volume is a data volume
    if (volumeToAttach == null || !(volumeToAttach.getVolumeType() == Volume.Type.DATADISK || volumeToAttach.getVolumeType() == Volume.Type.ROOT)) {
        throw new InvalidParameterValueException("Please specify a volume with the valid type: " + Volume.Type.ROOT.toString() + " or " + Volume.Type.DATADISK.toString());
    }
    // Check that the volume is not currently attached to any VM
    if (volumeToAttach.getInstanceId() != null) {
        throw new InvalidParameterValueException("Please specify a volume that is not attached to any VM.");
    }
    // Check that the volume is not destroyed
    if (volumeToAttach.getState() == Volume.State.Destroy) {
        throw new InvalidParameterValueException("Please specify a volume that is not destroyed.");
    }
    // Check that the virtual machine ID is valid and it's a user vm
    UserVmVO vm = _userVmDao.findById(vmId);
    if (vm == null || vm.getType() != VirtualMachine.Type.User) {
        throw new InvalidParameterValueException("Please specify a valid User VM.");
    }
    // Check that the VM is in the correct state
    if (vm.getState() != State.Running && vm.getState() != State.Stopped) {
        throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
    }
    // Check that the VM and the volume are in the same zone
    if (vm.getDataCenterId() != volumeToAttach.getDataCenterId()) {
        throw new InvalidParameterValueException("Please specify a VM that is in the same zone as the volume.");
    }
    // Check that the device ID is valid
    if (deviceId != null) {
        // validate ROOT volume type
        if (deviceId.longValue() == 0) {
            validateRootVolumeDetachAttach(_volsDao.findById(volumeToAttach.getId()), vm);
            // vm shouldn't have any volume with deviceId 0
            if (!_volsDao.findByInstanceAndDeviceId(vm.getId(), 0).isEmpty()) {
                throw new InvalidParameterValueException("Vm already has root volume attached to it");
            }
            // volume can't be in Uploaded state
            if (volumeToAttach.getState() == Volume.State.Uploaded) {
                throw new InvalidParameterValueException("No support for Root volume attach in state " + Volume.State.Uploaded);
            }
        }
    }
    // that supported by hypervisor
    if (deviceId == null || deviceId.longValue() != 0) {
        List<VolumeVO> existingDataVolumes = _volsDao.findByInstanceAndType(vmId, Volume.Type.DATADISK);
        int maxAttachableDataVolumesSupported = getMaxDataVolumesSupported(vm);
        if (existingDataVolumes.size() >= maxAttachableDataVolumesSupported) {
            throw new InvalidParameterValueException("The specified VM already has the maximum number of data disks (" + maxAttachableDataVolumesSupported + ") attached. Please specify another VM.");
        }
    }
    // If local storage is disabled then attaching a volume with local disk
    // offering not allowed
    DataCenterVO dataCenter = _dcDao.findById(volumeToAttach.getDataCenterId());
    if (!dataCenter.isLocalStorageEnabled()) {
        DiskOfferingVO diskOffering = _diskOfferingDao.findById(volumeToAttach.getDiskOfferingId());
        if (diskOffering.isUseLocalStorage()) {
            throw new InvalidParameterValueException("Zone is not configured to use local storage but volume's disk offering " + diskOffering.getName() + " uses it");
        }
    }
    // if target VM has associated VM snapshots
    List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.findByVm(vmId);
    if (vmSnapshots.size() > 0) {
        throw new InvalidParameterValueException("Unable to attach volume, please specify a VM that does not have VM snapshots");
    }
    // if target VM has backups
    if (vm.getBackupOfferingId() != null || vm.getBackupVolumeList().size() > 0) {
        throw new InvalidParameterValueException("Unable to attach volume, please specify a VM that does not have any backups");
    }
    // permission check
    _accountMgr.checkAccess(caller, null, true, volumeToAttach, vm);
    if (!(Volume.State.Allocated.equals(volumeToAttach.getState()) || Volume.State.Ready.equals(volumeToAttach.getState()) || Volume.State.Uploaded.equals(volumeToAttach.getState()))) {
        throw new InvalidParameterValueException("Volume state must be in Allocated, Ready or in Uploaded state");
    }
    Account owner = _accountDao.findById(volumeToAttach.getAccountId());
    if (!(volumeToAttach.getState() == Volume.State.Allocated || volumeToAttach.getState() == Volume.State.Ready)) {
        try {
            _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, volumeToAttach.getSize());
        } catch (ResourceAllocationException e) {
            s_logger.error("primary storage resource limit check failed", e);
            throw new InvalidParameterValueException(e.getMessage());
        }
    }
    HypervisorType rootDiskHyperType = vm.getHypervisorType();
    HypervisorType volumeToAttachHyperType = _volsDao.getHypervisorType(volumeToAttach.getId());
    StoragePoolVO volumeToAttachStoragePool = _storagePoolDao.findById(volumeToAttach.getPoolId());
    // only perform this check if the volume's storage pool is not null and not managed
    if (volumeToAttachStoragePool != null && !volumeToAttachStoragePool.isManaged()) {
        if (volumeToAttachHyperType != HypervisorType.None && rootDiskHyperType != volumeToAttachHyperType) {
            throw new InvalidParameterValueException("Can't attach a volume created by: " + volumeToAttachHyperType + " to a " + rootDiskHyperType + " vm");
        }
    }
    AsyncJobExecutionContext asyncExecutionContext = AsyncJobExecutionContext.getCurrentExecutionContext();
    if (asyncExecutionContext != null) {
        AsyncJob job = asyncExecutionContext.getJob();
        if (s_logger.isInfoEnabled()) {
            s_logger.info("Trying to attaching volume " + volumeId + " to vm instance:" + vm.getId() + ", update async job-" + job.getId() + " progress status");
        }
        _jobMgr.updateAsyncJobAttachment(job.getId(), "Volume", volumeId);
    }
    AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
    if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
        // avoid re-entrance
        VmWorkJobVO placeHolder = null;
        placeHolder = createPlaceHolderWork(vmId);
        try {
            return orchestrateAttachVolumeToVM(vmId, volumeId, deviceId);
        } finally {
            _workJobDao.expunge(placeHolder.getId());
        }
    } else {
        Outcome<Volume> outcome = attachVolumeToVmThroughJobQueue(vmId, volumeId, deviceId);
        Volume vol = null;
        try {
            outcome.get();
        } catch (InterruptedException e) {
            throw new RuntimeException("Operation is interrupted", e);
        } catch (java.util.concurrent.ExecutionException e) {
            throw new RuntimeException("Execution excetion", e);
        }
        Object jobResult = _jobMgr.unmarshallResultObject(outcome.getJob());
        if (jobResult != null) {
            if (jobResult instanceof ConcurrentOperationException) {
                throw (ConcurrentOperationException) jobResult;
            } else if (jobResult instanceof InvalidParameterValueException) {
                throw (InvalidParameterValueException) jobResult;
            } else if (jobResult instanceof RuntimeException) {
                throw (RuntimeException) jobResult;
            } else if (jobResult instanceof Throwable) {
                throw new RuntimeException("Unexpected exception", (Throwable) jobResult);
            } else if (jobResult instanceof Long) {
                vol = _volsDao.findById((Long) jobResult);
            }
        }
        return vol;
    }
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) AsyncJobExecutionContext(org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext) VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) AsyncJob(org.apache.cloudstack.framework.jobs.AsyncJob) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) DataCenterVO(com.cloud.dc.DataCenterVO) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) EndPoint(org.apache.cloudstack.engine.subsystem.api.storage.EndPoint) VmWorkJobVO(org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) ExecutionException(java.util.concurrent.ExecutionException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) VmWorkDetachVolume(com.cloud.vm.VmWorkDetachVolume) VmWorkMigrateVolume(com.cloud.vm.VmWorkMigrateVolume) VmWorkResizeVolume(com.cloud.vm.VmWorkResizeVolume) VmWorkAttachVolume(com.cloud.vm.VmWorkAttachVolume) VmWorkExtractVolume(com.cloud.vm.VmWorkExtractVolume) DataObject(org.apache.cloudstack.engine.subsystem.api.storage.DataObject)

Example 22 with VMSnapshotVO

use of com.cloud.vm.snapshot.VMSnapshotVO in project cloudstack by apache.

the class UserVmManagerImpl method restoreVirtualMachine.

@Override
public UserVm restoreVirtualMachine(final Account caller, final long vmId, final Long newTemplateId) throws InsufficientCapacityException, ResourceUnavailableException {
    Long userId = caller.getId();
    _userDao.findById(userId);
    UserVmVO vm = _vmDao.findById(vmId);
    Account owner = _accountDao.findById(vm.getAccountId());
    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;
    }
    VMTemplateVO currentTemplate = _templateDao.findById(vm.getTemplateId());
    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 && currentTemplate != null && !currentTemplate.isDeployAsIs()) {
        InvalidParameterValueException ex = new InvalidParameterValueException("There are " + rootVols.size() + " root volumes for VM " + vm.getUuid());
        ex.addProxyObject(vm.getUuid(), "vmId");
        throw ex;
    }
    // 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 = getRestoreVirtualMachineTemplate(caller, newTemplateId, rootVols, vm);
    checkRestoreVmFromTemplate(vm, template);
    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;
        }
    }
    List<Volume> newVols = new ArrayList<>();
    for (VolumeVO root : rootVols) {
        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 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);
                } else {
                    newVol = volumeMgr.allocateDuplicateVolume(root, newTemplateId);
                    vm.setGuestOSId(template.getGuestOSId());
                    vm.setTemplateId(newTemplateId);
                }
                // check and update VM if it can be dynamically scalable with the new template
                updateVMDynamicallyScalabilityUsingTemplate(vm, newTemplateId);
            } else {
                newVol = volumeMgr.allocateDuplicateVolume(root, null);
            }
            newVols.add(newVol);
            if (userVmDetailsDao.findDetail(vm.getId(), VmDetailConstants.ROOT_DISK_SIZE) == null && !newVol.getSize().equals(template.getSize())) {
                VolumeVO resizedVolume = (VolumeVO) newVol;
                if (template.getSize() != null) {
                    resizedVolume.setSize(template.getSize());
                    _volsDao.update(resizedVolume.getId(), resizedVolume);
                }
            }
            // 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.isEnablePassword()) {
        password = _mgr.generateRandomPassword();
        boolean result = resetVMPasswordInternal(vmId, password);
        if (!result) {
            throw new CloudRuntimeException("VM reset is completed but failed to reset password for the virtual machine ");
        }
        vm.setPassword(password);
    }
    if (needRestart) {
        try {
            if (vm.getDetail(VmDetailConstants.PASSWORD) != null) {
                params = new HashMap<>();
                params.put(VirtualMachineProfile.Param.VmPassword, password);
            }
            _itMgr.start(vm.getUuid(), params);
            vm = _vmDao.findById(vmId);
            if (template.isEnablePassword()) {
                // 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(VmDetailConstants.PASSWORD) != null) {
                        userVmDetailsDao.removeDetail(vm.getId(), VmDetailConstants.PASSWORD);
                    }
                    _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) ArrayList(java.util.ArrayList) 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) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) InsufficientServerCapacityException(com.cloud.exception.InsufficientServerCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) IOException(java.io.IOException) UnsupportedServiceException(com.cloud.exception.UnsupportedServiceException) 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) AffinityConflictException(com.cloud.exception.AffinityConflictException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConfigurationException(javax.naming.ConfigurationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) 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 23 with VMSnapshotVO

use of com.cloud.vm.snapshot.VMSnapshotVO in project cloudstack by apache.

the class VolumeApiServiceImplTest method setup.

@Before
public void setup() throws InterruptedException, ExecutionException {
    Mockito.lenient().doReturn(volumeMockId).when(volumeDataStoreVoMock).getVolumeId();
    Mockito.doReturn(volumeMockId).when(volumeVoMock).getId();
    Mockito.lenient().doReturn(accountMockId).when(accountMock).getId();
    Mockito.doReturn(volumeSizeMock).when(volumeVoMock).getSize();
    Mockito.doReturn(volumeSizeMock).when(newDiskOfferingMock).getDiskSize();
    Mockito.doReturn(Mockito.mock(VolumeApiResult.class)).when(asyncCallFutureVolumeapiResultMock).get();
    Mockito.when(storagePoolMock.getId()).thenReturn(storagePoolMockId);
    volumeApiServiceImpl._gson = GsonHelper.getGsonLogger();
    // mock caller context
    AccountVO account = new AccountVO("admin", 1L, "networkDomain", Account.ACCOUNT_TYPE_NORMAL, "uuid");
    UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
    CallContext.register(user, account);
    // mock async context
    AsyncJobExecutionContext context = new AsyncJobExecutionContext();
    AsyncJobExecutionContext.init(_jobMgr, _joinMapDao);
    AsyncJobVO job = new AsyncJobVO();
    context.setJob(job);
    AsyncJobExecutionContext.setCurrentExecutionContext(context);
    TransactionLegacy txn = TransactionLegacy.open("runVolumeDaoImplTest");
    try {
        // volume of running vm id=1
        VolumeVO volumeOfRunningVm = new VolumeVO("root", 1L, 1L, 1L, 1L, 1L, "root", "root", Storage.ProvisioningType.THIN, 1, null, null, "root", Volume.Type.ROOT);
        when(volumeDaoMock.findById(1L)).thenReturn(volumeOfRunningVm);
        UserVmVO runningVm = new UserVmVO(1L, "vm", "vm", 1, HypervisorType.XenServer, 1L, false, false, 1L, 1L, 1, 1L, null, "vm");
        runningVm.setState(State.Running);
        runningVm.setDataCenterId(1L);
        when(userVmDaoMock.findById(1L)).thenReturn(runningVm);
        // volume of stopped vm id=2
        VolumeVO volumeOfStoppedVm = new VolumeVO("root", 1L, 1L, 1L, 1L, 2L, "root", "root", Storage.ProvisioningType.THIN, 1, null, null, "root", Volume.Type.ROOT);
        volumeOfStoppedVm.setPoolId(1L);
        when(volumeDaoMock.findById(2L)).thenReturn(volumeOfStoppedVm);
        UserVmVO stoppedVm = new UserVmVO(2L, "vm", "vm", 1, HypervisorType.XenServer, 1L, false, false, 1L, 1L, 1, 1L, null, "vm");
        stoppedVm.setState(State.Stopped);
        stoppedVm.setDataCenterId(1L);
        when(userVmDaoMock.findById(2L)).thenReturn(stoppedVm);
        // volume of hyperV vm id=3
        UserVmVO hyperVVm = new UserVmVO(3L, "vm", "vm", 1, HypervisorType.Hyperv, 1L, false, false, 1L, 1L, 1, 1L, null, "vm");
        hyperVVm.setState(State.Stopped);
        hyperVVm.setDataCenterId(1L);
        when(userVmDaoMock.findById(3L)).thenReturn(hyperVVm);
        VolumeVO volumeOfStoppeHyperVVm = new VolumeVO("root", 1L, 1L, 1L, 1L, 3L, "root", "root", Storage.ProvisioningType.THIN, 1, null, null, "root", Volume.Type.ROOT);
        volumeOfStoppeHyperVVm.setPoolId(1L);
        when(volumeDaoMock.findById(3L)).thenReturn(volumeOfStoppeHyperVVm);
        StoragePoolVO unmanagedPool = new StoragePoolVO();
        when(primaryDataStoreDaoMock.findById(1L)).thenReturn(unmanagedPool);
        // volume of managed pool id=4
        StoragePoolVO managedPool = new StoragePoolVO();
        managedPool.setManaged(true);
        when(primaryDataStoreDaoMock.findById(2L)).thenReturn(managedPool);
        VolumeVO managedPoolVolume = new VolumeVO("root", 1L, 1L, 1L, 1L, 2L, "root", "root", Storage.ProvisioningType.THIN, 1, null, null, "root", Volume.Type.ROOT);
        managedPoolVolume.setPoolId(2L);
        when(volumeDaoMock.findById(4L)).thenReturn(managedPoolVolume);
        // non-root non-datadisk volume
        VolumeInfo volumeWithIncorrectVolumeType = Mockito.mock(VolumeInfo.class);
        lenient().when(volumeWithIncorrectVolumeType.getId()).thenReturn(5L);
        when(volumeWithIncorrectVolumeType.getVolumeType()).thenReturn(Volume.Type.ISO);
        when(volumeDataFactoryMock.getVolume(5L)).thenReturn(volumeWithIncorrectVolumeType);
        // correct root volume
        VolumeInfo correctRootVolume = Mockito.mock(VolumeInfo.class);
        when(correctRootVolume.getId()).thenReturn(6L);
        when(correctRootVolume.getDataCenterId()).thenReturn(1L);
        when(correctRootVolume.getVolumeType()).thenReturn(Volume.Type.ROOT);
        when(correctRootVolume.getInstanceId()).thenReturn(null);
        when(correctRootVolume.getState()).thenReturn(Volume.State.Ready);
        when(correctRootVolume.getTemplateId()).thenReturn(null);
        when(correctRootVolume.getPoolId()).thenReturn(1L);
        when(volumeDataFactoryMock.getVolume(6L)).thenReturn(correctRootVolume);
        VolumeVO correctRootVolumeVO = new VolumeVO("root", 1L, 1L, 1L, 1L, 2L, "root", "root", Storage.ProvisioningType.THIN, 1, null, null, "root", Volume.Type.ROOT);
        when(volumeDaoMock.findById(6L)).thenReturn(correctRootVolumeVO);
        // managed root volume
        VolumeInfo managedVolume = Mockito.mock(VolumeInfo.class);
        when(managedVolume.getId()).thenReturn(7L);
        when(managedVolume.getDataCenterId()).thenReturn(1L);
        when(managedVolume.getVolumeType()).thenReturn(Volume.Type.ROOT);
        when(managedVolume.getInstanceId()).thenReturn(null);
        lenient().when(managedVolume.getPoolId()).thenReturn(2L);
        when(volumeDataFactoryMock.getVolume(7L)).thenReturn(managedVolume);
        VolumeVO managedVolume1 = new VolumeVO("root", 1L, 1L, 1L, 1L, 2L, "root", "root", Storage.ProvisioningType.THIN, 1, null, null, "root", Volume.Type.ROOT);
        managedVolume1.setPoolId(2L);
        managedVolume1.setDataCenterId(1L);
        when(volumeDaoMock.findById(7L)).thenReturn(managedVolume1);
        // vm having root volume
        UserVmVO vmHavingRootVolume = new UserVmVO(4L, "vm", "vm", 1, HypervisorType.XenServer, 1L, false, false, 1L, 1L, 1, 1L, null, "vm");
        vmHavingRootVolume.setState(State.Stopped);
        vmHavingRootVolume.setDataCenterId(1L);
        when(userVmDaoMock.findById(4L)).thenReturn(vmHavingRootVolume);
        List<VolumeVO> vols = new ArrayList<VolumeVO>();
        vols.add(new VolumeVO());
        when(volumeDaoMock.findByInstanceAndDeviceId(4L, 0L)).thenReturn(vols);
        // volume in uploaded state
        VolumeInfo uploadedVolume = Mockito.mock(VolumeInfo.class);
        when(uploadedVolume.getId()).thenReturn(8L);
        when(uploadedVolume.getDataCenterId()).thenReturn(1L);
        when(uploadedVolume.getVolumeType()).thenReturn(Volume.Type.ROOT);
        when(uploadedVolume.getInstanceId()).thenReturn(null);
        lenient().when(uploadedVolume.getPoolId()).thenReturn(1L);
        when(uploadedVolume.getState()).thenReturn(Volume.State.Uploaded);
        when(volumeDataFactoryMock.getVolume(8L)).thenReturn(uploadedVolume);
        VolumeVO upVolume = new VolumeVO("root", 1L, 1L, 1L, 1L, 2L, "root", "root", Storage.ProvisioningType.THIN, 1, null, null, "root", Volume.Type.ROOT);
        upVolume.setPoolId(1L);
        upVolume.setDataCenterId(1L);
        upVolume.setState(Volume.State.Uploaded);
        when(volumeDaoMock.findById(8L)).thenReturn(upVolume);
        // helper dao methods mock
        when(_vmSnapshotDao.findByVm(any(Long.class))).thenReturn(new ArrayList<VMSnapshotVO>());
        when(_vmInstanceDao.findById(any(Long.class))).thenReturn(stoppedVm);
        DataCenterVO enabledZone = Mockito.mock(DataCenterVO.class);
        when(enabledZone.getAllocationState()).thenReturn(Grouping.AllocationState.Enabled);
        when(_dcDao.findById(anyLong())).thenReturn(enabledZone);
    } finally {
        txn.close("runVolumeDaoImplTest");
    }
    // helper methods mock
    lenient().doNothing().when(accountManagerMock).checkAccess(any(Account.class), any(AccessType.class), any(Boolean.class), any(ControlledEntity.class));
    doNothing().when(_jobMgr).updateAsyncJobAttachment(any(Long.class), any(String.class), any(Long.class));
    when(_jobMgr.submitAsyncJob(any(AsyncJobVO.class), any(String.class), any(Long.class))).thenReturn(1L);
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) AsyncJobExecutionContext(org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext) ArrayList(java.util.ArrayList) VolumeInfo(org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo) VolumeApiResult(org.apache.cloudstack.engine.subsystem.api.storage.VolumeService.VolumeApiResult) Matchers.anyString(org.mockito.Matchers.anyString) AccountVO(com.cloud.user.AccountVO) AsyncJobVO(org.apache.cloudstack.framework.jobs.impl.AsyncJobVO) TransactionLegacy(com.cloud.utils.db.TransactionLegacy) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) UserVO(com.cloud.user.UserVO) ControlledEntity(org.apache.cloudstack.acl.ControlledEntity) StoragePoolVO(org.apache.cloudstack.storage.datastore.db.StoragePoolVO) Matchers.anyLong(org.mockito.Matchers.anyLong) AccessType(org.apache.cloudstack.acl.SecurityChecker.AccessType) Before(org.junit.Before)

Example 24 with VMSnapshotVO

use of com.cloud.vm.snapshot.VMSnapshotVO in project cloudstack by apache.

the class ProjectManagerImpl method deleteProject.

@Override
@ActionEvent(eventType = EventTypes.EVENT_PROJECT_DELETE, eventDescription = "deleting project", async = true)
public boolean deleteProject(long projectId, Boolean isCleanup) {
    CallContext ctx = CallContext.current();
    ProjectVO project = getProject(projectId);
    // verify input parameters
    if (project == null) {
        throw new InvalidParameterValueException("Unable to find project by id " + projectId);
    }
    CallContext.current().setProject(project);
    _accountMgr.checkAccess(ctx.getCallingAccount(), AccessType.ModifyProject, true, _accountMgr.getAccount(project.getProjectAccountId()));
    if (isCleanup != null && isCleanup) {
        return deleteProject(ctx.getCallingAccount(), ctx.getCallingUserId(), project);
    } else {
        List<VMTemplateVO> userTemplates = _templateDao.listByAccountId(project.getProjectAccountId());
        List<VMSnapshotVO> vmSnapshots = _vmSnapshotDao.listByAccountId(project.getProjectAccountId());
        List<UserVmVO> vms = _userVmDao.listByAccountId(project.getProjectAccountId());
        List<VolumeVO> volumes = _volumeDao.findDetachedByAccount(project.getProjectAccountId());
        List<NetworkVO> networks = _networkDao.listByOwner(project.getProjectAccountId());
        List<? extends Vpc> vpcs = _vpcMgr.getVpcsForAccount(project.getProjectAccountId());
        Optional<String> message = Stream.of(userTemplates, vmSnapshots, vms, volumes, networks, vpcs).filter(entity -> !entity.isEmpty()).map(entity -> entity.size() + " " + entity.get(0).getEntityType().getSimpleName() + " to clean up").findFirst();
        if (message.isEmpty()) {
            return deleteProject(ctx.getCallingAccount(), ctx.getCallingUserId(), project);
        }
        CloudRuntimeException e = new CloudRuntimeException("Can't delete the project yet because it has " + message.get());
        e.addProxyObject(project.getUuid(), "projectId");
        throw e;
    }
}
Also used : Role(com.cloud.projects.ProjectAccount.Role) SMTPMailSender(org.apache.cloudstack.utils.mailing.SMTPMailSender) MessagingException(javax.mail.MessagingException) Transaction(com.cloud.utils.db.Transaction) DomainManager(com.cloud.user.DomainManager) TransactionCallbackWithExceptionNoReturn(com.cloud.utils.db.TransactionCallbackWithExceptionNoReturn) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) MailAddress(org.apache.cloudstack.utils.mailing.MailAddress) SecureRandom(java.security.SecureRandom) ResourceType(com.cloud.configuration.Resource.ResourceType) Logger(org.apache.log4j.Logger) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) Map(java.util.Map) ResourceLimitService(com.cloud.user.ResourceLimitService) DomainDao(com.cloud.domain.dao.DomainDao) Config(com.cloud.configuration.Config) CallContext(org.apache.cloudstack.context.CallContext) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ManagedContextRunnable(org.apache.cloudstack.managed.context.ManagedContextRunnable) TransactionCallback(com.cloud.utils.db.TransactionCallback) TimeZone(java.util.TimeZone) TransactionStatus(com.cloud.utils.db.TransactionStatus) ProjectRole(org.apache.cloudstack.acl.ProjectRole) ProjectJoinDao(com.cloud.api.query.dao.ProjectJoinDao) Set(java.util.Set) ApiDBUtils(com.cloud.api.ApiDBUtils) Account(com.cloud.user.Account) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) VpcManager(com.cloud.network.vpc.VpcManager) VMSnapshotDao(com.cloud.vm.snapshot.dao.VMSnapshotDao) List(java.util.List) Stream(java.util.stream.Stream) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) Optional(java.util.Optional) AccountDao(com.cloud.user.dao.AccountDao) ProjectRoleDao(org.apache.cloudstack.acl.dao.ProjectRoleDao) UnsupportedEncodingException(java.io.UnsupportedEncodingException) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) ManagerBase(com.cloud.utils.component.ManagerBase) ProjectAccountJoinDao(com.cloud.api.query.dao.ProjectAccountJoinDao) VMTemplateDao(com.cloud.storage.dao.VMTemplateDao) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) AccessType(org.apache.cloudstack.acl.SecurityChecker.AccessType) BooleanUtils(org.apache.commons.lang3.BooleanUtils) ConfigurationException(javax.naming.ConfigurationException) NetworkDao(com.cloud.network.dao.NetworkDao) EventTypes(com.cloud.event.EventTypes) ProjectInvitationDao(com.cloud.projects.dao.ProjectInvitationDao) Inject(javax.inject.Inject) HashSet(java.util.HashSet) ConfigKey(org.apache.cloudstack.framework.config.ConfigKey) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UserDao(com.cloud.user.dao.UserDao) State(com.cloud.projects.Project.State) User(com.cloud.user.User) NetworkVO(com.cloud.network.dao.NetworkVO) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) VolumeDao(com.cloud.storage.dao.VolumeDao) Configurable(org.apache.cloudstack.framework.config.Configurable) NamedThreadFactory(com.cloud.utils.concurrency.NamedThreadFactory) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ProjectDao(com.cloud.projects.dao.ProjectDao) VMTemplateVO(com.cloud.storage.VMTemplateVO) SMTPMailProperties(org.apache.cloudstack.utils.mailing.SMTPMailProperties) ConfigurationManager(com.cloud.configuration.ConfigurationManager) Vpc(com.cloud.network.vpc.Vpc) AccountVO(com.cloud.user.AccountVO) UserVmDao(com.cloud.vm.dao.UserVmDao) DB(com.cloud.utils.db.DB) ResourceTagDao(com.cloud.tags.dao.ResourceTagDao) TimeUnit(java.util.concurrent.TimeUnit) UserVmVO(com.cloud.vm.UserVmVO) Component(org.springframework.stereotype.Component) ProjectAccountDao(com.cloud.projects.dao.ProjectAccountDao) ProjectInvitationJoinDao(com.cloud.api.query.dao.ProjectInvitationJoinDao) ActionEvent(com.cloud.event.ActionEvent) AccountManager(com.cloud.user.AccountManager) DomainVO(com.cloud.domain.DomainVO) ConfigurationDao(org.apache.cloudstack.framework.config.dao.ConfigurationDao) VolumeVO(com.cloud.storage.VolumeVO) UserVmVO(com.cloud.vm.UserVmVO) NetworkVO(com.cloud.network.dao.NetworkVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) CallContext(org.apache.cloudstack.context.CallContext) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ActionEvent(com.cloud.event.ActionEvent)

Example 25 with VMSnapshotVO

use of com.cloud.vm.snapshot.VMSnapshotVO in project cloudstack by apache.

the class AccountManagerImplTest method deleteUserAccount.

@Test
public void deleteUserAccount() {
    AccountVO account = new AccountVO();
    account.setId(42l);
    DomainVO domain = new DomainVO();
    Mockito.when(_accountDao.findById(42l)).thenReturn(account);
    Mockito.doNothing().when(accountManagerImpl).checkAccess(Mockito.any(Account.class), Mockito.isNull(), Mockito.anyBoolean(), Mockito.any(Account.class));
    Mockito.when(_accountDao.remove(42l)).thenReturn(true);
    Mockito.when(_configMgr.releaseAccountSpecificVirtualRanges(42l)).thenReturn(true);
    Mockito.lenient().when(_domainMgr.getDomain(Mockito.anyLong())).thenReturn(domain);
    Mockito.lenient().when(securityChecker.checkAccess(Mockito.any(Account.class), Mockito.any(Domain.class))).thenReturn(true);
    Mockito.when(_vmSnapshotDao.listByAccountId(Mockito.anyLong())).thenReturn(new ArrayList<VMSnapshotVO>());
    List<SSHKeyPairVO> sshkeyList = new ArrayList<SSHKeyPairVO>();
    SSHKeyPairVO sshkey = new SSHKeyPairVO();
    sshkey.setId(1l);
    sshkeyList.add(sshkey);
    Mockito.when(_sshKeyPairDao.listKeyPairs(Mockito.anyLong(), Mockito.anyLong())).thenReturn(sshkeyList);
    Mockito.when(_sshKeyPairDao.remove(Mockito.anyLong())).thenReturn(true);
    Assert.assertTrue(accountManagerImpl.deleteUserAccount(42l));
    // assert that this was a clean delete
    Mockito.verify(_accountDao, Mockito.never()).markForCleanup(Mockito.eq(42l));
}
Also used : DomainVO(com.cloud.domain.DomainVO) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) ArrayList(java.util.ArrayList) Domain(com.cloud.domain.Domain) ProjectAccountVO(com.cloud.projects.ProjectAccountVO) Test(org.junit.Test)

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