use of com.cloud.exception.ResourceAllocationException in project cloudstack by apache.
the class UserVmManagerImpl method verifyVmLimits.
private void verifyVmLimits(UserVmVO vmInstance, Map<String, String> details) {
Account owner = _accountDao.findById(vmInstance.getAccountId());
if (owner == null) {
throw new InvalidParameterValueException("The owner of " + vmInstance + " does not exist: " + vmInstance.getAccountId());
}
long newCpu = NumberUtils.toLong(details.get(VmDetailConstants.CPU_NUMBER));
long newMemory = NumberUtils.toLong(details.get(VmDetailConstants.MEMORY));
ServiceOfferingVO currentServiceOffering = _serviceOfferingDao.findByIdIncludingRemoved(vmInstance.getId(), vmInstance.getServiceOfferingId());
ServiceOfferingVO svcOffering = _serviceOfferingDao.findById(vmInstance.getServiceOfferingId());
boolean isDynamic = currentServiceOffering.isDynamic();
if (isDynamic) {
Map<String, String> customParameters = new HashMap<>();
customParameters.put(VmDetailConstants.CPU_NUMBER, String.valueOf(newCpu));
customParameters.put(VmDetailConstants.MEMORY, String.valueOf(newMemory));
customParameters.put(VmDetailConstants.CPU_SPEED, details.get(VmDetailConstants.CPU_SPEED));
validateCustomParameters(svcOffering, customParameters);
}
if (VirtualMachineManager.ResourceCountRunningVMsonly.value()) {
return;
}
long currentCpu = currentServiceOffering.getCpu();
long currentMemory = currentServiceOffering.getRamSize();
try {
if (newCpu > currentCpu) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.cpu, newCpu - currentCpu);
}
if (newMemory > currentMemory) {
_resourceLimitMgr.checkResourceLimit(owner, ResourceType.memory, newMemory - currentMemory);
}
} catch (ResourceAllocationException e) {
s_logger.error(String.format("Failed to updated VM due to: %s", e.getLocalizedMessage()));
throw new InvalidParameterValueException(e.getLocalizedMessage());
}
if (newCpu > currentCpu) {
_resourceLimitMgr.incrementResourceCount(owner.getAccountId(), ResourceType.cpu, newCpu - currentCpu);
} else if (newCpu > 0 && currentCpu > newCpu) {
_resourceLimitMgr.decrementResourceCount(owner.getAccountId(), ResourceType.cpu, currentCpu - newCpu);
}
if (newMemory > currentMemory) {
_resourceLimitMgr.incrementResourceCount(owner.getAccountId(), ResourceType.memory, newMemory - currentMemory);
} else if (newMemory > 0 && currentMemory > newMemory) {
_resourceLimitMgr.decrementResourceCount(owner.getAccountId(), ResourceType.memory, currentMemory - newMemory);
}
}
use of com.cloud.exception.ResourceAllocationException in project cloudstack by apache.
the class UserVmManagerImpl method recoverVirtualMachine.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VM_RECOVER, eventDescription = "Recovering VM")
public UserVm recoverVirtualMachine(RecoverVMCmd cmd) throws ResourceAllocationException, CloudRuntimeException {
final Long vmId = cmd.getId();
Account caller = CallContext.current().getCallingAccount();
final Long userId = caller.getAccountId();
// Verify input parameters
final UserVmVO vm = _vmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
}
// When trying to expunge, permission is denied when the caller is not an admin and the AllowUserExpungeRecoverVm is false for the caller.
if (!_accountMgr.isAdmin(userId) && !AllowUserExpungeRecoverVm.valueIn(userId)) {
throw new PermissionDeniedException("Recovering a vm can only be done by an Admin. Or when the allow.user.expunge.recover.vm key is set.");
}
if (vm.getRemoved() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Unable to find vm or vm is removed: " + vmId);
}
throw new InvalidParameterValueException("Unable to find vm by id " + vmId);
}
if (vm.getState() != State.Destroyed) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("vm is not in the right state: " + vmId);
}
throw new InvalidParameterValueException("Vm with id " + vmId + " is not in the right state");
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Recovering vm " + vmId);
}
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<ResourceAllocationException>() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) throws ResourceAllocationException {
Account account = _accountDao.lockRow(vm.getAccountId(), true);
// if the account is deleted, throw error
if (account.getRemoved() != null) {
throw new CloudRuntimeException("Unable to recover VM as the account is deleted");
}
// Get serviceOffering for Virtual Machine
ServiceOfferingVO serviceOffering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
// accountId will not be exceeded
if (!VirtualMachineManager.ResourceCountRunningVMsonly.value()) {
resourceLimitCheck(account, vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
}
_haMgr.cancelDestroy(vm, vm.getHostId());
try {
if (!_itMgr.stateTransitTo(vm, VirtualMachine.Event.RecoveryRequested, null)) {
s_logger.debug("Unable to recover the vm because it is not in the correct state: " + vmId);
throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
}
} catch (NoTransitionException e) {
throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
}
// Recover the VM's disks
List<VolumeVO> volumes = _volsDao.findByInstance(vmId);
for (VolumeVO volume : volumes) {
if (volume.getVolumeType().equals(Volume.Type.ROOT)) {
// Create an event
Long templateId = volume.getTemplateId();
Long diskOfferingId = volume.getDiskOfferingId();
Long offeringId = null;
if (diskOfferingId != null) {
DiskOfferingVO offering = _diskOfferingDao.findById(diskOfferingId);
if (offering != null && !offering.isComputeOnly()) {
offeringId = offering.getId();
}
}
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), offeringId, templateId, volume.getSize(), Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
}
}
// Update Resource Count for the given account
resourceCountIncrement(account.getId(), vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
}
});
return _vmDao.findById(vmId);
}
use of com.cloud.exception.ResourceAllocationException in project cloudstack by apache.
the class UserVmManagerImpl method startVirtualMachine.
private UserVm startVirtualMachine(long vmId, Long podId, Long clusterId, Long hostId, Map<Long, DiskOffering> diskOfferingMap, Map<VirtualMachineProfile.Param, Object> additonalParams, String deploymentPlannerToUse) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException {
UserVmVO vm = _vmDao.findById(vmId);
Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> vmParamPair = null;
try {
vmParamPair = startVirtualMachine(vmId, podId, clusterId, hostId, additonalParams, deploymentPlannerToUse);
vm = vmParamPair.first();
// At this point VM should be in "Running" state
UserVmVO tmpVm = _vmDao.findById(vm.getId());
if (!tmpVm.getState().equals(State.Running)) {
// Some other thread changed state of VM, possibly vmsync
s_logger.error("VM " + tmpVm + " unexpectedly went to " + tmpVm.getState() + " state");
throw new ConcurrentOperationException("Failed to deploy VM " + vm);
}
try {
if (!diskOfferingMap.isEmpty()) {
List<VolumeVO> vols = _volsDao.findByInstance(tmpVm.getId());
for (VolumeVO vol : vols) {
if (vol.getVolumeType() == Volume.Type.DATADISK) {
DiskOffering doff = _entityMgr.findById(DiskOffering.class, vol.getDiskOfferingId());
_volService.resizeVolumeOnHypervisor(vol.getId(), doff.getDiskSize(), tmpVm.getHostId(), vm.getInstanceName());
}
}
}
} catch (Exception e) {
s_logger.fatal("Unable to resize the data disk for vm " + vm.getDisplayName() + " due to " + e.getMessage(), e);
}
} finally {
updateVmStateForFailedVmCreation(vm.getId(), hostId);
}
// Check that the password was passed in and is valid
VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId());
if (template.isEnablePassword()) {
// this value is not being sent to the backend; need only for api
// display purposes
vm.setPassword((String) vmParamPair.second().get(VirtualMachineProfile.Param.VmPassword));
}
return vm;
}
use of com.cloud.exception.ResourceAllocationException in project cosmic by MissionCriticalCloud.
the class CreateStorageNetworkIpRangeCmd method execute.
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
try {
final StorageNetworkIpRange result = _storageNetworkService.createIpRange(this);
final StorageNetworkIpRangeResponse response = _responseGenerator.createStorageNetworkIpRangeResponse(result);
response.setResponseName(getCommandName());
setResponseObject(response);
} catch (final Exception e) {
s_logger.warn("Create storage network IP range failed", e);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
}
}
use of com.cloud.exception.ResourceAllocationException in project cosmic by MissionCriticalCloud.
the class UpdateStorageNetworkIpRangeCmd method execute.
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
try {
final StorageNetworkIpRange result = _storageNetworkService.updateIpRange(this);
final StorageNetworkIpRangeResponse response = _responseGenerator.createStorageNetworkIpRangeResponse(result);
response.setResponseName(getCommandName());
this.setResponseObject(response);
} catch (final Exception e) {
s_logger.warn("Update storage network IP range failed", e);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
}
}
Aggregations