use of com.cloud.legacymodel.exceptions.ResourceAllocationException in project cosmic by MissionCriticalCloud.
the class ApiDispatcher method dispatch.
public void dispatch(final BaseCmd cmd, final Map<String, String> params, final boolean execute) throws CloudException {
// Let the chain of responsibility dispatch gradually
standardDispatchChain.dispatch(new DispatchTask(cmd, params));
final CallContext ctx = CallContext.current();
ctx.setEventDisplayEnabled(cmd.isDisplay());
if (params.get(ApiConstants.PROJECT_ID) != null) {
final Project project = _entityMgr.findByUuidIncludingRemoved(Project.class, params.get(ApiConstants.PROJECT_ID));
ctx.setProject(project);
}
// TODO This if shouldn't be here. Use polymorphism and move it to validateSpecificParameters
if (cmd instanceof BaseAsyncCmd) {
final BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmd;
final String startEventId = params.get(ApiConstants.CTX_START_EVENT_ID);
ctx.setStartEventId(Long.parseLong(startEventId));
// Synchronise job on the object if needed
if (asyncCmd.getJob() != null && asyncCmd.getSyncObjId() != null && asyncCmd.getSyncObjType() != null) {
final Long queueSizeLimit;
if (asyncCmd.getSyncObjType() != null && asyncCmd.getSyncObjType().equalsIgnoreCase(BaseAsyncCmd.snapshotHostSyncObject)) {
queueSizeLimit = _createSnapshotQueueSizeLimit;
} else {
queueSizeLimit = 1L;
}
if (queueSizeLimit != null) {
if (!execute) {
// if we are not within async-execution context, enqueue the command
_asyncMgr.syncAsyncJobExecution((AsyncJob) asyncCmd.getJob(), asyncCmd.getSyncObjType(), asyncCmd.getSyncObjId().longValue(), queueSizeLimit);
return;
}
} else {
s_logger.trace("The queue size is unlimited, skipping the synchronizing");
}
}
}
// TODO This if shouldn't be here. Use polymorphism and move it to validateSpecificParameters
if (cmd instanceof BaseAsyncCustomIdCmd) {
((BaseAsyncCustomIdCmd) cmd).checkUuid();
} else if (cmd instanceof BaseCustomIdCmd) {
((BaseCustomIdCmd) cmd).checkUuid();
}
try {
cmd.execute();
} catch (ResourceUnavailableException | InsufficientCapacityException | ResourceAllocationException | NetworkRuleConflictException e) {
throw new CloudException("Caught exception while executing command", e);
}
}
use of com.cloud.legacymodel.exceptions.ResourceAllocationException in project cosmic by MissionCriticalCloud.
the class IpAddressManagerImpl method associateIPToGuestNetwork.
@DB
@Override
public IPAddressVO associateIPToGuestNetwork(final long ipId, final long networkId, final boolean releaseOnFailure) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException {
final Account caller = CallContext.current().getCallingAccount();
Account owner = null;
final IPAddressVO ipToAssoc = _ipAddressDao.findById(ipId);
if (ipToAssoc != null) {
final Network network = _networksDao.findById(networkId);
if (network == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
final DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
if (zone.getNetworkType() == NetworkType.Advanced) {
if (network.getGuestType() == GuestType.Shared) {
if (isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) {
_accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.UseEntry, false, network);
} else {
throw new InvalidParameterValueException("IP can be associated with guest network of 'shared' type only if " + "network services Source Nat, Static Nat, Port Forwarding, Load balancing, firewall are enabled in the network");
}
}
} else {
_accountMgr.checkAccess(caller, null, true, ipToAssoc);
}
owner = _accountMgr.getAccount(ipToAssoc.getAllocatedToAccountId());
} else {
s_logger.debug("Unable to find ip address by id: " + ipId);
return null;
}
if (ipToAssoc.getAssociatedWithNetworkId() != null) {
s_logger.debug("IP " + ipToAssoc + " is already assocaited with network id" + networkId);
return ipToAssoc;
}
final Network network = _networksDao.findById(networkId);
if (network != null) {
_accountMgr.checkAccess(owner, AccessType.UseEntry, false, network);
} else {
s_logger.debug("Unable to find ip address by id: " + ipId);
return null;
}
final DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
// allow associating IP addresses to guest network only
if (network.getTrafficType() != TrafficType.Guest) {
throw new InvalidParameterValueException("Ip address can be associated to the network with trafficType " + TrafficType.Guest);
}
// - and it belongs to the system
if (network.getAccountId() != owner.getId()) {
if (zone.getNetworkType() != NetworkType.Basic && !(zone.getNetworkType() == NetworkType.Advanced && network.getGuestType() == GuestType.Shared)) {
throw new InvalidParameterValueException("The owner of the network is not the same as owner of the IP");
}
}
if (zone.getNetworkType() == NetworkType.Advanced) {
// In Advance zone allow to do IP assoc only for Isolated networks with source nat service enabled
if (network.getGuestType() == GuestType.Isolated && !(_networkModel.areServicesSupportedInNetwork(network.getId(), Service.SourceNat))) {
throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated only to the network of guest type " + GuestType.Isolated + " with the " + Service.SourceNat.getName() + " enabled");
}
// In Advance zone allow to do IP assoc only for shared networks with source nat/static nat/lb/pf services enabled
if (network.getGuestType() == GuestType.Shared && !isSharedNetworkOfferingWithServices(network.getNetworkOfferingId())) {
throw new InvalidParameterValueException("In zone of type " + NetworkType.Advanced + " ip address can be associated with network of guest type " + GuestType.Shared + "only if at " + "least one of the services " + Service.SourceNat.getName() + "/" + Service.StaticNat.getName() + "/" + Service.Lb.getName() + "/" + Service.PortForwarding.getName() + " is enabled");
}
}
s_logger.debug("Associating ip " + ipToAssoc + " to network " + network);
final IPAddressVO ip = _ipAddressDao.findById(ipId);
// update ip address with networkId
ip.setAssociatedWithNetworkId(networkId);
_ipAddressDao.update(ipId, ip);
boolean success = false;
try {
success = applyIpAssociations(network, false);
if (success) {
s_logger.debug("Successfully associated ip address " + ip.getAddress().addr() + " to network " + network);
} else {
s_logger.warn("Failed to associate ip address " + ip.getAddress().addr() + " to network " + network);
}
return ip;
} finally {
if (!success && releaseOnFailure) {
if (ip != null) {
try {
s_logger.warn("Failed to associate ip address, so releasing ip from the database " + ip);
_ipAddressDao.markAsUnavailable(ip.getId());
if (!applyIpAssociations(network, true)) {
// if fail to apply ip assciations again, unassign ip address without updating resource
// count and generating usage event as there is no need to keep it in the db
_ipAddressDao.unassignIpAddress(ip.getId());
}
} catch (final Exception e) {
s_logger.warn("Unable to disassociate ip address for recovery", e);
}
}
}
}
}
use of com.cloud.legacymodel.exceptions.ResourceAllocationException in project cosmic by MissionCriticalCloud.
the class VolumeApiServiceImpl method resizeVolume.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_RESIZE, eventDescription = "resizing volume", async = true)
public VolumeVO resizeVolume(final ResizeVolumeCmd cmd) throws ResourceAllocationException {
Long newSize;
Long newMinIops;
Long newMaxIops;
final boolean shrinkOk = cmd.getShrinkOk();
final VolumeVO volume = this._volsDao.findById(cmd.getEntityId());
if (volume == null) {
throw new InvalidParameterValueException("No such volume");
}
/* Does the caller have authority to act on this volume? */
this._accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, volume);
if (volume.getInstanceId() != null) {
// Check that Vm to which this volume is attached does not have VM Snapshots
if (this._vmSnapshotDao.findByVm(volume.getInstanceId()).size() > 0) {
throw new InvalidParameterValueException("Volume cannot be resized which is attached to VM with VM Snapshots");
}
}
final DiskOfferingVO diskOffering = this._diskOfferingDao.findById(volume.getDiskOfferingId());
DiskOfferingVO newDiskOffering = null;
if (cmd.getNewDiskOfferingId() != null && volume.getDiskOfferingId() != cmd.getNewDiskOfferingId()) {
newDiskOffering = this._diskOfferingDao.findById(cmd.getNewDiskOfferingId());
}
if (newDiskOffering != null && !newDiskOffering.isCustomized()) {
throw new InvalidParameterValueException("The disk offering for volume " + volume.getName() + " can only be changed to an offering that supports a custom disk size.");
}
if (diskOffering.isCustomized() && newDiskOffering != null && !newDiskOffering.isCustomized()) {
throw new InvalidParameterValueException("Volume " + volume.getName() + " has a custom size disk offering. Cannot change the disk offering." + " Please change the size instead");
}
final HypervisorType hypervisorType = this._volsDao.getHypervisorType(volume.getId());
if (hypervisorType != HypervisorType.KVM && hypervisorType != HypervisorType.XenServer && hypervisorType != HypervisorType.Any && hypervisorType != HypervisorType.None) {
throw new InvalidParameterValueException("CloudStack currently supports volume resize only on KVM, or XenServer.");
}
if (volume.getState() != Volume.State.Ready && volume.getState() != Volume.State.Allocated) {
throw new InvalidParameterValueException("Volume should be in ready or allocated state before attempting a resize. Volume " + volume.getUuid() + " is in state " + volume.getState() + ".");
}
// if we are to use the existing disk offering
if (newDiskOffering == null) {
newSize = cmd.getSize();
// if the caller is looking to change the size of the volume
if (newSize != null) {
if (!diskOffering.isCustomized() && !volume.getVolumeType().equals(VolumeType.ROOT)) {
throw new InvalidParameterValueException("To change a volume's size without providing a new disk offering, its current disk offering must be " + "customizable or it must be a root volume (if providing a disk offering, make sure it is different from the current disk offering).");
}
// convert from bytes to GiB
newSize = newSize << 30;
} else {
// no parameter provided; just use the original size of the volume
newSize = volume.getSize();
}
newMinIops = cmd.getMinIops();
if (newMinIops != null) {
if (diskOffering.isCustomizedIops() == null || !diskOffering.isCustomizedIops()) {
throw new InvalidParameterValueException("The current disk offering does not support customization of the 'Min IOPS' parameter.");
}
} else {
// no parameter provided; just use the original min IOPS of the volume
newMinIops = volume.getMinIops();
}
newMaxIops = cmd.getMaxIops();
if (newMaxIops != null) {
if (diskOffering.isCustomizedIops() == null || !diskOffering.isCustomizedIops()) {
throw new InvalidParameterValueException("The current disk offering does not support customization of the 'Max IOPS' parameter.");
}
} else {
// no parameter provided; just use the original max IOPS of the volume
newMaxIops = volume.getMaxIops();
}
validateIops(newMinIops, newMaxIops);
} else {
if (newDiskOffering.getRemoved() != null) {
throw new InvalidParameterValueException("Requested disk offering has been removed.");
}
if (!DiskOfferingVO.Type.Disk.equals(newDiskOffering.getType())) {
throw new InvalidParameterValueException("Requested disk offering type is invalid.");
}
if (diskOffering.getTags() != null) {
if (!StringUtils.areTagsEqual(diskOffering.getTags(), newDiskOffering.getTags())) {
throw new InvalidParameterValueException("The tags on the new and old disk offerings must match.");
}
} else if (newDiskOffering.getTags() != null) {
throw new InvalidParameterValueException("There are no tags on the current disk offering. The new disk offering needs to have no tags, as well.");
}
if (!areIntegersEqual(diskOffering.getHypervisorSnapshotReserve(), newDiskOffering.getHypervisorSnapshotReserve())) {
throw new InvalidParameterValueException("The hypervisor snapshot reverse on the new and old disk offerings must be equal.");
}
if (newDiskOffering.getDomainId() != null) {
// not a public offering; check access
this._configMgr.checkDiskOfferingAccess(CallContext.current().getCallingAccount(), newDiskOffering);
}
if (newDiskOffering.isCustomized()) {
newSize = cmd.getSize();
if (newSize == null) {
throw new InvalidParameterValueException("The new disk offering requires that a size be specified.");
}
// convert from bytes to GiB
newSize = newSize << 30;
} else {
newSize = newDiskOffering.getDiskSize();
}
if (!volume.getSize().equals(newSize) && !volume.getVolumeType().equals(VolumeType.DATADISK)) {
throw new InvalidParameterValueException("Only data volumes can be resized via a new disk offering.");
}
if (newDiskOffering.isCustomizedIops() != null && newDiskOffering.isCustomizedIops()) {
newMinIops = cmd.getMinIops() != null ? cmd.getMinIops() : volume.getMinIops();
newMaxIops = cmd.getMaxIops() != null ? cmd.getMaxIops() : volume.getMaxIops();
validateIops(newMinIops, newMaxIops);
} else {
newMinIops = newDiskOffering.getMinIops();
newMaxIops = newDiskOffering.getMaxIops();
}
}
final long currentSize = volume.getSize();
// if the caller is looking to change the size of the volume
if (currentSize != newSize) {
if (!validateVolumeSizeRange(newSize)) {
throw new InvalidParameterValueException("Requested size out of range");
}
/*
* Let's make certain they (think they) know what they're doing if they
* want to shrink by forcing them to provide the shrinkok parameter.
* This will be checked again at the hypervisor level where we can see
* the actual disk size.
*/
if (currentSize > newSize && !shrinkOk) {
throw new InvalidParameterValueException("Going from existing size of " + currentSize + " to size of " + newSize + " would shrink the volume." + "Need to sign off by supplying the shrinkok parameter with value of true.");
}
if (newSize > currentSize) {
/* Check resource limit for this account on primary storage resource */
this._resourceLimitMgr.checkResourceLimit(this._accountMgr.getAccount(volume.getAccountId()), ResourceType.primary_storage, volume.isDisplayVolume(), new Long(newSize - currentSize).longValue());
}
}
/* If this volume has never been beyond allocated state, short circuit everything and simply update the database. */
if (volume.getState() == Volume.State.Allocated) {
s_logger.debug("Volume is in the allocated state, but has never been created. Simply updating database with new size and IOPS.");
volume.setSize(newSize);
volume.setMinIops(newMinIops);
volume.setMaxIops(newMaxIops);
if (newDiskOffering != null) {
volume.setDiskOfferingId(cmd.getNewDiskOfferingId());
}
this._volsDao.update(volume.getId(), volume);
return volume;
}
final UserVmVO userVm = this._userVmDao.findById(volume.getInstanceId());
if (userVm != null) {
// serialize VM operation
final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
final VmWorkJobVO placeHolder;
placeHolder = createPlaceHolderWork(userVm.getId());
try {
return orchestrateResizeVolume(volume.getId(), currentSize, newSize, newMinIops, newMaxIops, newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
} finally {
this._workJobDao.expunge(placeHolder.getId());
}
} else {
final Outcome<Volume> outcome = resizeVolumeThroughJobQueue(userVm.getId(), volume.getId(), currentSize, newSize, newMinIops, newMaxIops, newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
try {
outcome.get();
} catch (final InterruptedException e) {
throw new RuntimeException("Operation was interrupted", e);
} catch (final java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution exception", e);
}
final Object jobResult = this._jobMgr.unmarshallResultObject(outcome.getJob());
if (jobResult != null) {
if (jobResult instanceof ConcurrentOperationException) {
throw (ConcurrentOperationException) jobResult;
} else if (jobResult instanceof ResourceAllocationException) {
throw (ResourceAllocationException) 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) {
return this._volsDao.findById((Long) jobResult);
}
}
return volume;
}
}
return orchestrateResizeVolume(volume.getId(), currentSize, newSize, newMinIops, newMaxIops, newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
}
use of com.cloud.legacymodel.exceptions.ResourceAllocationException in project cosmic by MissionCriticalCloud.
the class ResourceLimitManagerImpl method checkResourceLimit.
@Override
@DB
public void checkResourceLimit(final Account account, final ResourceType type, final long... count) throws ResourceAllocationException {
final long numResources = ((count.length == 0) ? 1 : count[0]);
Project project = null;
// Don't place any limits on system or root admin accounts
if (this._accountMgr.isRootAdmin(account.getId())) {
return;
}
if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
project = this._projectDao.findByProjectAccountId(account.getId());
}
final Project projectFinal = project;
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<ResourceAllocationException>() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) throws ResourceAllocationException {
// Lock all rows first so nobody else can read it
final Set<Long> rowIdsToLock = ResourceLimitManagerImpl.this._resourceCountDao.listAllRowsToUpdate(account.getId(), ResourceOwnerType.Account, type);
final SearchCriteria<ResourceCountVO> sc = ResourceLimitManagerImpl.this.ResourceCountSearch.create();
sc.setParameters("id", rowIdsToLock.toArray());
ResourceLimitManagerImpl.this._resourceCountDao.lockRows(sc, null, true);
// Check account limits
final long accountLimit = findCorrectResourceLimitForAccount(account, type);
final long potentialCount = ResourceLimitManagerImpl.this._resourceCountDao.getResourceCount(account.getId(), ResourceOwnerType.Account, type) + numResources;
if (accountLimit != Resource.RESOURCE_UNLIMITED && potentialCount > accountLimit) {
String message = "Maximum number of resources of type '" + type + "' for account name=" + account.getAccountName() + " in domain id=" + account.getDomainId() + " has been exceeded.";
if (projectFinal != null) {
message = "Maximum number of resources of type '" + type + "' for project name=" + projectFinal.getName() + " in domain id=" + account.getDomainId() + " has been exceeded.";
}
final ResourceAllocationException e = new ResourceAllocationException(message, type);
s_logger.error(message, e);
throw e;
}
// check all domains in the account's domain hierarchy
Long domainId;
if (projectFinal != null) {
domainId = projectFinal.getDomainId();
} else {
domainId = account.getDomainId();
}
while (domainId != null) {
final DomainVO domain = ResourceLimitManagerImpl.this._domainDao.findById(domainId);
// no limit check if it is ROOT domain
if (domainId != Domain.ROOT_DOMAIN) {
final long domainLimit = findCorrectResourceLimitForDomain(domain, type);
final long domainCount = ResourceLimitManagerImpl.this._resourceCountDao.getResourceCount(domainId, ResourceOwnerType.Domain, type) + numResources;
if (domainLimit != Resource.RESOURCE_UNLIMITED && domainCount > domainLimit) {
throw new ResourceAllocationException("Maximum number of resources of type '" + type + "' for domain id=" + domainId + " has been exceeded.", type);
}
}
domainId = domain.getParent();
}
}
});
}
use of com.cloud.legacymodel.exceptions.ResourceAllocationException in project cosmic by MissionCriticalCloud.
the class AclOnPrivateGwTest method testExecuteFail.
@Test
public void testExecuteFail() {
final VpcService vpcService = Mockito.mock(VpcService.class);
createPrivateGwCmd._vpcService = vpcService;
try {
Mockito.when(vpcService.applyVpcPrivateGateway(Matchers.anyLong(), Matchers.anyBoolean())).thenReturn(null);
} catch (final ResourceUnavailableException e) {
e.printStackTrace();
} catch (final ConcurrentOperationException e) {
e.printStackTrace();
}
try {
createPrivateGwCmd.execute();
} catch (final ServerApiException exception) {
Assert.assertEquals("Failed to create private gateway", exception.getDescription());
} catch (final ResourceAllocationException e) {
e.printStackTrace();
} catch (final InsufficientCapacityException e) {
e.printStackTrace();
} catch (final ConcurrentOperationException e) {
e.printStackTrace();
} catch (final ResourceUnavailableException e) {
e.printStackTrace();
}
}
Aggregations