use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.
the class StorageManagerImpl method createPool.
@Override
public PrimaryDataStoreInfo createPool(final CreateStoragePoolCmd cmd) throws ResourceInUseException, IllegalArgumentException, UnknownHostException, ResourceUnavailableException {
final String providerName = cmd.getStorageProviderName();
DataStoreProvider storeProvider = this._dataStoreProviderMgr.getDataStoreProvider(providerName);
if (storeProvider == null) {
storeProvider = this._dataStoreProviderMgr.getDefaultPrimaryDataStoreProvider();
if (storeProvider == null) {
throw new InvalidParameterValueException("can't find storage provider: " + providerName);
}
}
Long clusterId = cmd.getClusterId();
Long podId = cmd.getPodId();
final Long zoneId = cmd.getZoneId();
ScopeType scopeType = ScopeType.CLUSTER;
final String scope = cmd.getScope();
if (scope != null) {
try {
scopeType = Enum.valueOf(ScopeType.class, scope.toUpperCase());
} catch (final Exception e) {
throw new InvalidParameterValueException("invalid scope for pool " + scope);
}
}
if (scopeType == ScopeType.CLUSTER && clusterId == null) {
throw new InvalidParameterValueException("cluster id can't be null, if scope is cluster");
} else if (scopeType == ScopeType.ZONE && zoneId == null) {
throw new InvalidParameterValueException("zone id can't be null, if scope is zone");
}
HypervisorType hypervisorType = HypervisorType.KVM;
if (scopeType == ScopeType.ZONE) {
// ignore passed clusterId and podId
clusterId = null;
podId = null;
final String hypervisor = cmd.getHypervisor();
if (hypervisor != null) {
try {
hypervisorType = HypervisorType.getType(hypervisor);
} catch (final Exception e) {
throw new InvalidParameterValueException("invalid hypervisor type " + hypervisor);
}
} else {
throw new InvalidParameterValueException("Missing parameter hypervisor. Hypervisor type is required to create zone wide primary storage.");
}
if (hypervisorType != HypervisorType.KVM && hypervisorType != HypervisorType.Any) {
throw new InvalidParameterValueException("zone wide storage pool is not supported for hypervisor type " + hypervisor);
}
}
final Map<String, String> details = extractApiParamAsMap(cmd.getDetails());
final DataCenterVO zone = this._dcDao.findById(cmd.getZoneId());
if (zone == null) {
throw new InvalidParameterValueException("unable to find zone by id " + zoneId);
}
// Check if zone is disabled
final Account account = CallContext.current().getCallingAccount();
if (AllocationState.Disabled == zone.getAllocationState() && !this._accountMgr.isRootAdmin(account.getId())) {
throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
}
final Map<String, Object> params = new HashMap<>();
params.put("zoneId", zone.getId());
params.put("clusterId", clusterId);
params.put("podId", podId);
params.put("url", cmd.getUrl());
params.put("tags", cmd.getTags());
params.put("name", cmd.getStoragePoolName());
params.put("details", details);
params.put("providerName", storeProvider.getName());
params.put("managed", cmd.isManaged());
params.put("capacityBytes", cmd.getCapacityBytes());
params.put("capacityIops", cmd.getCapacityIops());
final DataStoreLifeCycle lifeCycle = storeProvider.getDataStoreLifeCycle();
DataStore store = null;
try {
store = lifeCycle.initialize(params);
if (scopeType == ScopeType.CLUSTER) {
final ClusterScope clusterScope = new ClusterScope(clusterId, podId, zoneId);
lifeCycle.attachCluster(store, clusterScope);
} else if (scopeType == ScopeType.ZONE) {
final ZoneScope zoneScope = new ZoneScope(zoneId);
lifeCycle.attachZone(store, zoneScope, hypervisorType);
}
} catch (final Exception e) {
s_logger.debug("Failed to add data store: " + e.getMessage(), e);
try {
// not deleting data store.
if (store != null) {
lifeCycle.deleteDataStore(store);
}
} catch (final Exception ex) {
s_logger.debug("Failed to clean up storage pool: " + ex.getMessage());
}
throw new CloudRuntimeException("Failed to add data store: " + e.getMessage(), e);
}
return (PrimaryDataStoreInfo) this._dataStoreMgr.getDataStore(store.getId(), DataStoreRole.Primary);
}
use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.
the class ResourceChecker method checkIfDataCenterIsUsable.
public void checkIfDataCenterIsUsable(final DataCenter dataCenter, final Account account) {
final long dataCenterId = dataCenter.getId();
logger.debug("Checking if data center " + dataCenterId + " is usable.");
if (AllocationState.Disabled == dataCenter.getAllocationState() && !accountManager.isRootAdmin(account.getId())) {
final PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation, data center with specified id is currently disabled");
ex.addProxyObject(dataCenter.getUuid(), "dcId");
throw ex;
}
logger.debug("Data center " + dataCenterId + "is usable");
}
use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method startVirtualMachine.
@Override
public Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> startVirtualMachine(final long vmId, final Long hostId, final Map<VirtualMachineProfile.Param, Object> additionalParams, final String deploymentPlannerToUse) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
// Input validation
final Account callerAccount = CallContext.current().getCallingAccount();
final UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
// if account is removed, return error
if (callerAccount != null && callerAccount.getRemoved() != null) {
throw new InvalidParameterValueException("The account " + callerAccount.getId() + " is removed");
}
final UserVmVO vm = _vmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("unable to find a virtual machine with id " + vmId);
}
_accountMgr.checkAccess(callerAccount, null, true, vm);
final Account owner = _accountDao.findById(vm.getAccountId());
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());
}
Host destinationHost = null;
if (hostId != null) {
final Account account = CallContext.current().getCallingAccount();
if (!_accountService.isRootAdmin(account.getId())) {
throw new PermissionDeniedException("Parameter hostid can only be specified by a Root Admin, permission denied");
}
destinationHost = _hostDao.findById(hostId);
if (destinationHost == null) {
throw new InvalidParameterValueException("Unable to find the host to deploy the VM, host id=" + hostId);
}
}
DataCenterDeployment plan = null;
boolean deployOnGivenHost = false;
if (destinationHost != null) {
s_logger.debug("Destination Host to deploy the VM is specified, specifying a deployment plan to deploy the VM");
plan = new DataCenterDeployment(vm.getDataCenterId(), destinationHost.getPodId(), destinationHost.getClusterId(), destinationHost.getId(), null, null);
deployOnGivenHost = true;
}
// Set parameters
Map<VirtualMachineProfile.Param, Object> params = null;
VMTemplateVO template = null;
if (vm.isUpdateParameters()) {
_vmDao.loadDetails(vm);
// Check that the password was passed in and is valid
template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId());
String password = "saved_password";
if (template.getEnablePassword()) {
if (vm.getDetail("password") != null) {
password = DBEncryptionUtil.decrypt(vm.getDetail("password"));
} else {
password = _mgr.generateRandomPassword();
}
}
if (!validPassword(password)) {
throw new InvalidParameterValueException("A valid password for this virtual machine was not provided.");
}
// 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);
params = new HashMap<>();
if (additionalParams != null) {
params.putAll(additionalParams);
}
params.put(VirtualMachineProfile.Param.VmPassword, password);
}
final VirtualMachineEntity vmEntity = _orchSrvc.getVirtualMachine(vm.getUuid());
DeploymentPlanner planner = null;
if (deploymentPlannerToUse != null) {
// if set to null, the deployment planner would be later figured out either from global config var, or from
// the service offering
planner = _planningMgr.getDeploymentPlannerByName(deploymentPlannerToUse);
if (planner == null) {
throw new InvalidParameterValueException("Can't find a planner by name " + deploymentPlannerToUse);
}
}
final String reservationId = vmEntity.reserve(planner, plan, new ExcludeList(), Long.toString(callerUser.getId()));
vmEntity.deploy(reservationId, Long.toString(callerUser.getId()), params, deployOnGivenHost);
final Pair<UserVmVO, Map<VirtualMachineProfile.Param, Object>> vmParamPair = new Pair(vm, params);
if (vm != null && vm.isUpdateParameters()) {
// Set date and version we start this VM
vm.setLastStartDateTime(getCurrentLocalDateTimeStamp());
vm.setLastStartVersion(UserVmManagerImpl.class.getPackage().getImplementationVersion());
// display purposes
if (template.getEnablePassword()) {
vm.setPassword((String) vmParamPair.second().get(VirtualMachineProfile.Param.VmPassword));
vm.setUpdateParameters(false);
if (vm.getDetail("password") != null) {
_vmDetailsDao.remove(_vmDetailsDao.findDetail(vm.getId(), "password").getId());
}
}
// Reset VM compliance state
if (vm.getComplianceStatus() == ComplianceStatus.VMNeedsRestart) {
vm.setComplianceStatus(ComplianceStatus.Compliant);
}
_vmDao.update(vm.getId(), vm);
}
return vmParamPair;
}
use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method migrateVirtualMachine.
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
public VirtualMachine migrateVirtualMachine(final Long vmId, final Host destinationHost) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
// access check - only root admin can migrate VM
final Account caller = CallContext.current().getCallingAccount();
if (!_accountMgr.isRootAdmin(caller.getId())) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Caller is not a root admin, permission denied to migrate the VM");
}
throw new PermissionDeniedException("No permission to migrate VM, Only Root Admin can migrate a VM!");
}
final VMInstanceVO vm = _vmInstanceDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("Unable to find the VM by id=" + vmId);
}
// business logic
if (vm.getState() != State.Running) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
}
final InvalidParameterValueException ex = new InvalidParameterValueException("VM is not Running, unable to migrate the vm with specified id");
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
if (serviceOfferingDetailsDao.findDetail(vm.getServiceOfferingId(), GPU.Keys.pciDevice.toString()) != null) {
throw new InvalidParameterValueException("Live Migration of GPU enabled VM is not supported");
}
if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.KVM)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(vm + " is not XenServer/KVM, cannot migrate this VM.");
}
throw new InvalidParameterValueException("Unsupported Hypervisor Type for VM migration, we support XenServer/KVM only");
}
if (isVMUsingLocalStorage(vm)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(vm + " is using Local Storage, cannot migrate this VM.");
}
throw new InvalidParameterValueException("Unsupported operation, VM uses Local storage, cannot migrate");
}
// check if migrating to same host
final long srcHostId = vm.getHostId();
if (destinationHost.getId() == srcHostId) {
throw new InvalidParameterValueException("Cannot migrate VM, VM is already presnt on this host, please specify valid destination host to migrate the VM");
}
// check if host is UP
if (destinationHost.getState() != HostStatus.Up || destinationHost.getResourceState() != ResourceState.Enabled) {
throw new InvalidParameterValueException("Cannot migrate VM, destination host is not in correct state, has status: " + destinationHost.getState() + ", state: " + destinationHost.getResourceState());
}
if (vm.getType() != VirtualMachineType.User) {
// for System VMs check that the destination host is within the same
// cluster
final HostVO srcHost = _hostDao.findById(srcHostId);
if (srcHost != null && srcHost.getClusterId() != null && destinationHost.getClusterId() != null) {
if (srcHost.getClusterId().longValue() != destinationHost.getClusterId().longValue()) {
throw new InvalidParameterValueException("Cannot migrate the VM, destination host is not in the same cluster as current host of the VM");
}
}
}
checkHostsDedication(vm, srcHostId, destinationHost.getId());
// call to core process
final Zone zone = zoneRepository.findById(destinationHost.getDataCenterId()).orElse(null);
final HostPodVO pod = _podDao.findById(destinationHost.getPodId());
final Cluster cluster = _clusterDao.findById(destinationHost.getClusterId());
final DeployDestination dest = new DeployDestination(zone, pod, cluster, destinationHost);
// check max guest vm limit for the destinationHost
final HostVO destinationHostVO = _hostDao.findById(destinationHost.getId());
if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Host name: " + destinationHost.getName() + ": " + destinationHost.getName() + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
}
throw new VirtualMachineMigrationException("Destination host: " + destinationHost.getName() + " already has max Running VMs(count includes system VMs), cannot migrate to this host");
}
// Check host tags
final ServiceOffering serviceOffering = _serviceOfferingDao.findById(vm.getServiceOfferingId());
if (serviceOffering != null) {
final String requiredHostTag = serviceOffering.getHostTag();
final List<String> hostTags = _hostTagsDao.gethostTags(destinationHost.getId());
boolean foundRequiredHostTag = false;
for (final String hostTag : hostTags) {
if (hostTag.equals(requiredHostTag)) {
foundRequiredHostTag = true;
break;
}
}
if (!foundRequiredHostTag && requiredHostTag != null) {
throw new VirtualMachineMigrationException("Destination host: " + destinationHost.getName() + " does not have required host tag " + requiredHostTag);
}
}
final UserVmVO uservm = _vmDao.findById(vmId);
if (uservm != null) {
collectVmDiskStatistics(uservm);
}
_itMgr.migrate(vm.getUuid(), srcHostId, dest);
final VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId);
if (vmInstance.getType().equals(VirtualMachineType.User)) {
return _vmDao.findById(vmId);
} else {
return vmInstance;
}
}
use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.
the class UserVmManagerImpl method recoverVirtualMachine.
@Override
@DB
public UserVm recoverVirtualMachine(final RecoverVMCmd cmd) throws ResourceAllocationException, CloudRuntimeException {
final Long vmId = cmd.getId();
final 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(final TransactionStatus status) throws ResourceAllocationException {
final 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
final ServiceOfferingVO serviceOffering = _serviceOfferingDao.findById(vm.getId(), vm.getServiceOfferingId());
// First check that the maximum number of UserVMs, CPU and Memory limit for the given
// accountId will not be exceeded
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 (final NoTransitionException e) {
throw new InvalidParameterValueException("Unable to recover the vm because it is not in the correct state: " + vmId);
}
// Recover the VM's disks
final List<VolumeVO> volumes = _volsDao.findByInstance(vmId);
for (final VolumeVO volume : volumes) {
if (volume.getVolumeType().equals(VolumeType.ROOT)) {
// Create an event
final Long templateId = volume.getTemplateId();
final Long diskOfferingId = volume.getDiskOfferingId();
Long offeringId = null;
if (diskOfferingId != null) {
final DiskOfferingVO offering = _diskOfferingDao.findById(diskOfferingId);
if (offering != null && offering.getType() == DiskOfferingVO.Type.Disk) {
offeringId = offering.getId();
}
}
}
}
// Update Resource Count for the given account
resourceCountIncrement(account.getId(), vm.isDisplayVm(), new Long(serviceOffering.getCpu()), new Long(serviceOffering.getRamSize()));
}
});
return _vmDao.findById(vmId);
}
Aggregations