use of com.cloud.exception.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();
}
}
use of com.cloud.exception.ResourceAllocationException in project cosmic by MissionCriticalCloud.
the class CreatePrivateNetworkTest method createInvalidlyHostedPrivateNetwork.
@Test
@DB
public void createInvalidlyHostedPrivateNetwork() {
final TransactionLegacy __txn;
__txn = TransactionLegacy.open("createInvalidlyHostedPrivateNetworkTest");
/* Network nw; */
try {
/* nw = */
networkService.createPrivateNetwork("bla", "fake", 1L, "vlan:1", "10.1.1.2", null, "10.1.1.1", "255.255.255.0", 1L, 1L, true, 1L);
/* nw = */
networkService.createPrivateNetwork("bla", "fake", 1L, "lswitch:3", "10.1.1.2", null, "10.1.1.1", "255.255.255.0", 1L, 1L, false, 1L);
boolean invalid = false;
boolean unsupported = false;
try {
/* nw = */
networkService.createPrivateNetwork("bla", "fake", 1, "bla:2", "10.1.1.2", null, "10.1.1.1", "255.255.255.0", 1, 1L, true, 1L);
} catch (final CloudRuntimeException e) {
Assert.assertEquals("unexpected parameter exception", "string 'bla:2' has an unknown BroadcastDomainType.", e.getMessage());
invalid = true;
}
try {
/* nw = */
networkService.createPrivateNetwork("bla", "fake", 1, "mido://4", "10.1.1.2", null, "10.1.1.1", "255.255.255.0", 1, 1L, false, 1L);
} catch (final InvalidParameterValueException e) {
Assert.assertEquals("unexpected parameter exception", "unsupported type of broadcastUri specified: mido://4", e.getMessage());
unsupported = true;
}
Assert.assertEquals("'bla' should not be accepted as scheme", true, invalid);
Assert.assertEquals("'mido' should not yet be supported as scheme", true, unsupported);
} catch (final ResourceAllocationException e) {
s_logger.error("no resources", e);
fail("no resources");
} catch (final ConcurrentOperationException e) {
s_logger.error("another one is in the way", e);
fail("another one is in the way");
} catch (final InsufficientCapacityException e) {
s_logger.error("no capacity", e);
fail("no capacity");
} finally {
__txn.close("createInvalidlyHostedPrivateNetworkTest");
}
}
use of com.cloud.exception.ResourceAllocationException in project cosmic by MissionCriticalCloud.
the class ApiServer method handleRequest.
@Override
public String handleRequest(final Map params, final String responseType, final StringBuilder auditTrailSb) throws ServerApiException {
checkCharacterInkParams(params);
final String response;
String[] command = null;
try {
command = (String[]) params.get("command");
if (command == null) {
s_logger.error("invalid request, no command sent");
if (s_logger.isTraceEnabled()) {
s_logger.trace("dumping request parameters");
for (final Object key : params.keySet()) {
final String keyStr = (String) key;
final String[] value = (String[]) params.get(key);
s_logger.trace(" key: " + keyStr + ", value: " + ((value == null) ? "'null'" : value[0]));
}
}
throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "Invalid request, no command sent");
} else {
// Don't allow Login/Logout APIs to go past this point
if (_authManager.getAPIAuthenticator(command[0]) != null) {
return null;
}
final Map<String, String> paramMap = new HashMap<>();
final Set keys = params.keySet();
final Iterator keysIter = keys.iterator();
while (keysIter.hasNext()) {
final String key = (String) keysIter.next();
if ("command".equalsIgnoreCase(key)) {
continue;
}
final String[] value = (String[]) params.get(key);
paramMap.put(key, value[0]);
}
final Class<?> cmdClass = getCmdClass(command[0]);
if (cmdClass != null) {
final APICommand annotation = cmdClass.getAnnotation(APICommand.class);
if (annotation == null) {
s_logger.error("No APICommand annotation found for class " + cmdClass.getCanonicalName());
throw new CloudRuntimeException("No APICommand annotation found for class " + cmdClass.getCanonicalName());
}
BaseCmd cmdObj = (BaseCmd) cmdClass.newInstance();
cmdObj = ComponentContext.inject(cmdObj);
cmdObj.configure();
cmdObj.setFullUrlParams(paramMap);
cmdObj.setResponseType(responseType);
cmdObj.setHttpMethod(paramMap.get(ApiConstants.HTTPMETHOD).toString());
// This is where the command is either serialized, or directly dispatched
final StringBuilder log = new StringBuilder();
response = queueCommand(cmdObj, paramMap, log);
buildAuditTrail(auditTrailSb, command[0], log.toString());
} else {
final String errorString = "Unknown API command: " + command[0];
s_logger.warn(errorString);
auditTrailSb.append(" " + errorString);
throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, errorString);
}
}
} catch (final InvalidParameterValueException ex) {
s_logger.info(ex.getMessage());
throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
} catch (final IllegalArgumentException ex) {
s_logger.info(ex.getMessage());
throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
} catch (final PermissionDeniedException ex) {
final ArrayList<ExceptionProxyObject> idList = ex.getIdProxyList();
if (idList != null) {
final StringBuffer buf = new StringBuffer();
for (final ExceptionProxyObject obj : idList) {
buf.append(obj.getDescription());
buf.append(":");
buf.append(obj.getUuid());
buf.append(" ");
}
s_logger.info("PermissionDenied: " + ex.getMessage() + " on objs: [" + buf.toString() + "]");
} else {
s_logger.info("PermissionDenied: " + ex.getMessage());
}
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, ex.getMessage(), ex);
} catch (final AccountLimitException ex) {
s_logger.info(ex.getMessage());
throw new ServerApiException(ApiErrorCode.ACCOUNT_RESOURCE_LIMIT_ERROR, ex.getMessage(), ex);
} catch (final InsufficientCapacityException ex) {
s_logger.info(ex.getMessage());
String errorMsg = ex.getMessage();
if (!_accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
// hide internal details to non-admin user for security reason
errorMsg = BaseCmd.USER_ERROR_MESSAGE;
}
throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, errorMsg, ex);
} catch (final ResourceAllocationException ex) {
s_logger.info(ex.getMessage());
throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage(), ex);
} catch (final ResourceUnavailableException ex) {
s_logger.info(ex.getMessage());
String errorMsg = ex.getMessage();
if (!_accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
// hide internal details to non-admin user for security reason
errorMsg = BaseCmd.USER_ERROR_MESSAGE;
}
throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, errorMsg, ex);
} catch (final ServerApiException ex) {
s_logger.info(ex.getDescription());
throw ex;
} catch (final Exception ex) {
s_logger.error("Unhandled exception executing api command: " + ((command == null) ? "null" : printCommand(command)), ex);
String errorMsg = ex.getMessage();
if (!_accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
// hide internal details to non-admin user for security reason
errorMsg = BaseCmd.USER_ERROR_MESSAGE;
}
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg, ex);
}
return response;
}
use of com.cloud.exception.ResourceAllocationException in project cosmic by MissionCriticalCloud.
the class GetUploadParamsForVolumeCmd method execute.
@Override
public void execute() throws ServerApiException {
try {
final GetUploadParamsResponse response = _volumeService.uploadVolume(this);
response.setResponseName(getCommandName());
setResponseObject(response);
} catch (MalformedURLException | ResourceAllocationException e) {
s_logger.error("exception while uploading volume", e);
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "exception while uploading a volume: " + e.getMessage());
}
}
use of com.cloud.exception.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 = _volsDao.findById(cmd.getEntityId());
if (volume == null) {
throw new InvalidParameterValueException("No such volume");
}
/* Does the caller have authority to act on this volume? */
_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 (_vmSnapshotDao.findByVm(volume.getInstanceId()).size() > 0) {
throw new InvalidParameterValueException("Volume cannot be resized which is attached to VM with VM Snapshots");
}
}
final DiskOfferingVO diskOffering = _diskOfferingDao.findById(volume.getDiskOfferingId());
DiskOfferingVO newDiskOffering = null;
if (cmd.getNewDiskOfferingId() != null && volume.getDiskOfferingId() != cmd.getNewDiskOfferingId()) {
newDiskOffering = _diskOfferingDao.findById(cmd.getNewDiskOfferingId());
}
/* Only works for KVM/XenServer/VMware (or "Any") for now, and volumes with 'None' since they're just allocated in DB */
final HypervisorType hypervisorType = _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(Volume.Type.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
_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(Volume.Type.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 */
_resourceLimitMgr.checkResourceLimit(_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());
}
_volsDao.update(volume.getId(), volume);
return volume;
}
final UserVmVO userVm = _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 {
_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 = _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 _volsDao.findById((Long) jobResult);
}
}
return volume;
}
}
return orchestrateResizeVolume(volume.getId(), currentSize, newSize, newMinIops, newMaxIops, newDiskOffering != null ? cmd.getNewDiskOfferingId() : null, shrinkOk);
}
Aggregations