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;
}
}
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;
}
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);
}
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;
}
}
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));
}
Aggregations