use of com.cloud.exception.InsufficientCapacityException in project cloudstack by apache.
the class UploadSslCertCmd method execute.
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException {
try {
SslCertResponse response = _certService.uploadSslCert(this);
setResponseObject(response);
response.setResponseName(getCommandName());
} catch (Exception e) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage());
}
}
use of com.cloud.exception.InsufficientCapacityException in project cloudstack by apache.
the class UserVmManagerImpl method restoreVMInternal.
public UserVm restoreVMInternal(Account caller, UserVmVO vm, Long newTemplateId) throws InsufficientCapacityException, ResourceUnavailableException {
Long userId = caller.getId();
Account owner = _accountDao.findById(vm.getAccountId());
_userDao.findById(userId);
long vmId = vm.getId();
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;
}
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) {
InvalidParameterValueException ex = new InvalidParameterValueException("There are " + rootVols.size() + " root volumes for VM " + vm.getUuid());
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
VolumeVO root = rootVols.get(0);
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 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 = null;
//newTemplateId can be either template or ISO id. In the following snippet based on the vm deployment (from template or ISO) it is handled accordingly
if (newTemplateId != null) {
template = _templateDao.findById(newTemplateId);
_accountMgr.checkAccess(caller, null, true, template);
if (isISO) {
if (!template.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Invalid ISO id provided to restore the VM ");
}
} else {
if (template.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Invalid template id provided to restore the VM ");
}
}
} else {
if (isISO && templateId == null) {
throw new CloudRuntimeException("Cannot restore the VM since there is no ISO attached to VM");
}
template = _templateDao.findById(templateId);
if (template == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Cannot find template/ISO for specified volumeid and vmId");
ex.addProxyObject(vm.getUuid(), "vmId");
ex.addProxyObject(root.getUuid(), "volumeId");
throw ex;
}
}
TemplateDataStoreVO tmplStore = _templateStoreDao.findByTemplateZoneReady(template.getId(), vm.getDataCenterId());
if (tmplStore == null) {
throw new InvalidParameterValueException("Cannot restore the vm as the template " + template.getUuid() + " isn't available in the zone");
}
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;
}
}
/* 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);
_vmDao.update(vmId, vm);
} else {
newVol = volumeMgr.allocateDuplicateVolume(root, newTemplateId);
vm.setGuestOSId(template.getGuestOSId());
vm.setTemplateId(newTemplateId);
_vmDao.update(vmId, vm);
}
} else {
newVol = volumeMgr.allocateDuplicateVolume(root, null);
}
// 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.getEnablePassword()) {
password = _mgr.generateRandomPassword();
boolean result = resetVMPasswordInternal(vmId, password);
if (result) {
vm.setPassword(password);
_vmDao.loadDetails(vm);
// update the password in vm_details table too
// Check if an SSH key pair was selected for the instance and if so
// use it to encrypt & save the vm password
encryptAndStorePassword(vm, password);
} else {
throw new CloudRuntimeException("VM reset is completed but failed to reset password for the virtual machine ");
}
}
if (needRestart) {
try {
if (vm.getDetail("password") != null) {
params = new HashMap<VirtualMachineProfile.Param, Object>();
params.put(VirtualMachineProfile.Param.VmPassword, password);
}
_itMgr.start(vm.getUuid(), params);
vm = _vmDao.findById(vmId);
if (template.getEnablePassword()) {
// 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("password") != null) {
_vmDetailsDao.remove(_vmDetailsDao.findDetail(vm.getId(), "password").getId());
}
_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.exception.InsufficientCapacityException in project cloudstack by apache.
the class ListVmwareDcsCmd method execute.
/////////////////////////////////////////////////////
/////////////// API Implementation///////////////////
/////////////////////////////////////////////////////
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException {
List<? extends VmwareDatacenter> vmwareDcList = null;
try {
vmwareDcList = _vmwareDatacenterService.listVmwareDatacenters(this);
} catch (InvalidParameterValueException ie) {
throw new InvalidParameterValueException("Invalid zone id " + getZoneId());
} catch (Exception e) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to find associated VMware DCs associated with zone " + getZoneId());
}
ListResponse<VmwareDatacenterResponse> response = new ListResponse<VmwareDatacenterResponse>();
List<VmwareDatacenterResponse> vmwareDcResponses = new ArrayList<VmwareDatacenterResponse>();
if (vmwareDcList != null && vmwareDcList.size() > 0) {
for (VmwareDatacenter vmwareDc : vmwareDcList) {
VmwareDatacenterResponse vmwareDcResponse = new VmwareDatacenterResponse();
vmwareDcResponse.setId(vmwareDc.getUuid());
vmwareDcResponse.setVcenter(vmwareDc.getVcenterHost());
vmwareDcResponse.setName(vmwareDc.getVmwareDatacenterName());
vmwareDcResponse.setZoneId(getZoneId());
vmwareDcResponse.setObjectName("VMwareDC");
vmwareDcResponses.add(vmwareDcResponse);
}
}
response.setResponses(vmwareDcResponses);
response.setResponseName(getCommandName());
setResponseObject(response);
}
use of com.cloud.exception.InsufficientCapacityException in project cloudstack by apache.
the class MidoNetElementTest method testImplement.
/*
* Test the standard case of implement with no errors.
*/
public void testImplement() {
//mock
MidonetApi api = mock(MidonetApi.class, RETURNS_DEEP_STUBS);
//mockAccountDao
AccountDao mockAccountDao = mock(AccountDao.class);
AccountVO mockAccountVO = mock(AccountVO.class);
when(mockAccountDao.findById(anyLong())).thenReturn(mockAccountVO);
when(mockAccountVO.getUuid()).thenReturn("1");
MidoNetElement elem = new MidoNetElement();
elem.setMidonetApi(api);
elem.setAccountDao(mockAccountDao);
//mockRPort
RouterPort mockRPort = mock(RouterPort.class);
when(mockRPort.getId()).thenReturn(UUID.fromString("550e8400-e29b-41d4-a716-446655440000"));
//mockBPort
BridgePort mockBPort = mock(BridgePort.class);
when(mockBPort.link(any(UUID.class))).thenReturn(mockBPort);
//mockPort
Port mockPort = mock(Port.class);
ResourceCollection<Port> peerPorts = new ResourceCollection<Port>(new ArrayList<Port>());
peerPorts.add(mockPort);
//mockBridge
Bridge mockBridge = mock(Bridge.class, RETURNS_DEEP_STUBS);
when(api.addBridge().tenantId(anyString()).name(anyString()).create()).thenReturn(mockBridge);
when(mockBridge.addInteriorPort().create()).thenReturn(mockBPort);
when(mockBridge.getPeerPorts()).thenReturn(peerPorts);
//mockRouter
Router mockRouter = mock(Router.class, RETURNS_DEEP_STUBS);
when(api.addRouter().tenantId(anyString()).name(anyString()).create()).thenReturn(mockRouter);
when(mockRouter.addInteriorRouterPort().create()).thenReturn(mockRPort);
//mockNetwork
Network mockNetwork = mock(Network.class);
when(mockNetwork.getAccountId()).thenReturn((long) 1);
when(mockNetwork.getGateway()).thenReturn("1.2.3.4");
when(mockNetwork.getCidr()).thenReturn("1.2.3.0/24");
when(mockNetwork.getId()).thenReturn((long) 2);
when(mockNetwork.getBroadcastDomainType()).thenReturn(Networks.BroadcastDomainType.Mido);
when(mockNetwork.getTrafficType()).thenReturn(Networks.TrafficType.Public);
boolean result = false;
try {
result = elem.implement(mockNetwork, null, null, null);
} catch (ConcurrentOperationException e) {
fail(e.getMessage());
} catch (InsufficientCapacityException e) {
fail(e.getMessage());
} catch (ResourceUnavailableException e) {
fail(e.getMessage());
}
assertEquals(result, true);
}
use of com.cloud.exception.InsufficientCapacityException in project cloudstack by apache.
the class ConsoleProxyManagerImpl method startProxy.
@Override
public ConsoleProxyVO startProxy(long proxyVmId, boolean ignoreRestartSetting) {
try {
ConsoleProxyVO proxy = _consoleProxyDao.findById(proxyVmId);
if (proxy.getState() == VirtualMachine.State.Running) {
return proxy;
}
String restart = _configDao.getValue(Config.ConsoleProxyRestart.key());
if (!ignoreRestartSetting && restart != null && restart.equalsIgnoreCase("false")) {
return null;
}
if (proxy.getState() == VirtualMachine.State.Stopped) {
_itMgr.advanceStart(proxy.getUuid(), null, null);
proxy = _consoleProxyDao.findById(proxy.getId());
return proxy;
}
// For VMs that are in Stopping, Starting, Migrating state, let client to wait by returning null
// as sooner or later, Starting/Migrating state will be transited to Running and Stopping will be transited
// to Stopped to allow Starting of it
s_logger.warn("Console proxy is not in correct state to be started: " + proxy.getState());
return null;
} catch (StorageUnavailableException e) {
s_logger.warn("Exception while trying to start console proxy", e);
return null;
} catch (InsufficientCapacityException e) {
s_logger.warn("Exception while trying to start console proxy", e);
return null;
} catch (ResourceUnavailableException e) {
s_logger.warn("Exception while trying to start console proxy", e);
return null;
} catch (ConcurrentOperationException e) {
s_logger.warn("Runtime Exception while trying to start console proxy", e);
return null;
} catch (CloudRuntimeException e) {
s_logger.warn("Runtime Exception while trying to start console proxy", e);
return null;
} catch (OperationTimedoutException e) {
s_logger.warn("Runtime Exception while trying to start console proxy", e);
return null;
}
}
Aggregations