Search in sources :

Example 21 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method destroyVm.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_DESTROY, eventDescription = "destroying Vm", async = true)
public UserVm destroyVm(final DestroyVMCmd cmd) throws ResourceUnavailableException, ConcurrentOperationException {
    final CallContext ctx = CallContext.current();
    final long vmId = cmd.getId();
    final boolean expunge = cmd.getExpunge();
    // When trying to expunge, permission is denied when the caller is not an admin and the AllowUserExpungeRecoverVm is false for the caller.
    if (expunge && !_accountMgr.isAdmin(ctx.getCallingAccount().getId()) && !AllowUserExpungeRecoverVm.valueIn(cmd.getEntityOwnerId())) {
        throw new PermissionDeniedException("Parameter " + ApiConstants.EXPUNGE + " can be passed by Admin only. Or when the allow.user.expunge.recover.vm key is set.");
    }
    final UserVm destroyedVm = destroyVm(vmId);
    if (expunge) {
        final UserVmVO vm = _vmDao.findById(vmId);
        if (!expunge(vm, ctx.getCallingUserId(), ctx.getCallingAccount())) {
            throw new CloudRuntimeException("Failed to expunge vm " + destroyedVm);
        }
    }
    return destroyedVm;
}
Also used : UserVm(com.cloud.uservm.UserVm) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) CallContext(com.cloud.context.CallContext) ActionEvent(com.cloud.event.ActionEvent)

Example 22 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method migrateVirtualMachineWithVolume.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MIGRATE, eventDescription = "migrating VM", async = true)
public VirtualMachine migrateVirtualMachineWithVolume(final Long vmId, final Host destinationHost, final Map<String, String> volumeToPool) throws ResourceUnavailableException, ConcurrentOperationException, ManagementServerException, VirtualMachineMigrationException {
    // Access check - only root administrator 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);
    }
    if (vm.getState() != State.Running) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("VM is not Running, unable to migrate the vm " + vm);
        }
        final CloudRuntimeException ex = new CloudRuntimeException("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)) {
        throw new InvalidParameterValueException("Unsupported hypervisor type for vm migration, we support" + " XenServer/KVM only");
    }
    final long srcHostId = vm.getHostId();
    final Host srcHost = _resourceMgr.getHost(srcHostId);
    if (srcHost == null) {
        throw new InvalidParameterValueException("Cannot migrate VM, there is not Host with id: " + srcHostId);
    }
    // Check if src and destination hosts are valid and migrating to same host
    if (destinationHost.getId() == srcHostId) {
        throw new InvalidParameterValueException("Cannot migrate VM, VM is already present on this host, please" + " specify valid destination host to migrate the VM");
    }
    // Check if the source and destination hosts are of the same type and support storage motion.
    if (!srcHost.getHypervisorType().equals(destinationHost.getHypervisorType())) {
        throw new CloudRuntimeException("The source and destination hosts are not of the same type " + "Source hypervisor type and version: " + srcHost.getHypervisorType().toString() + " " + srcHost.getHypervisorVersion() + ", Destination hypervisor type and version: " + destinationHost.getHypervisorType().toString() + " " + destinationHost.getHypervisorVersion());
    }
    if (srcHost.getHypervisorVersion() != null && !srcHost.getHypervisorVersion().equals(destinationHost.getHypervisorVersion())) {
        throw new CloudRuntimeException("The source and destination hosts are not of the same version. " + "Source hypervisor type and version: " + srcHost.getHypervisorType().toString() + " " + srcHost.getHypervisorVersion() + ", Destination hypervisor type and version: " + destinationHost.getHypervisorType().toString() + " " + destinationHost.getHypervisorVersion());
    }
    final HypervisorCapabilitiesVO capabilities = _hypervisorCapabilitiesDao.findByHypervisorTypeAndVersion(srcHost.getHypervisorType(), srcHost.getHypervisorVersion());
    if (!capabilities.isStorageMotionSupported()) {
        throw new CloudRuntimeException("Migration with storage isn't supported on hypervisor " + srcHost.getHypervisorType() + " of version " + srcHost.getHypervisorVersion());
    }
    // Check if destination host is up.
    if (destinationHost.getState() != HostStatus.Up || destinationHost.getResourceState() != ResourceState.Enabled) {
        throw new CloudRuntimeException("Cannot migrate VM, destination host is not in correct state, has " + "status: " + destinationHost.getState() + ", state: " + destinationHost.getResourceState());
    }
    // Check that Vm does not have VM Snapshots
    if (_vmSnapshotDao.findByVm(vmId).size() > 0) {
        throw new InvalidParameterValueException("VM with VM Snapshots cannot be migrated with storage, please remove all VM snapshots");
    }
    final List<VolumeVO> vmVolumes = _volsDao.findUsableVolumesForInstance(vm.getId());
    final Map<Long, Long> volToPoolObjectMap = new HashMap<>();
    if (!isVMUsingLocalStorage(vm) && destinationHost.getClusterId().equals(srcHost.getClusterId())) {
        if (volumeToPool.isEmpty()) {
            // then fail the call. migrateVirtualMachine api should have been used.
            throw new InvalidParameterValueException("Migration of the vm " + vm + "from host " + srcHost + " to destination host " + destinationHost + " doesn't involve migrating the volumes.");
        }
    }
    if (!volumeToPool.isEmpty()) {
        // Check if all the volumes and pools passed as parameters are valid.
        for (final Map.Entry<String, String> entry : volumeToPool.entrySet()) {
            final VolumeVO volume = _volsDao.findByUuid(entry.getKey());
            final StoragePoolVO pool = _storagePoolDao.findByUuid(entry.getValue());
            if (volume == null) {
                throw new InvalidParameterValueException("There is no volume present with the given id " + entry.getKey());
            } else if (pool == null) {
                throw new InvalidParameterValueException("There is no storage pool present with the given id " + entry.getValue());
            } else if (pool.isInMaintenance()) {
                throw new InvalidParameterValueException("Cannot migrate volume " + volume + "to the destination storage pool " + pool.getName() + " as the storage pool is in maintenance mode.");
            } else {
                // Verify the volume given belongs to the vm.
                if (!vmVolumes.contains(volume)) {
                    throw new InvalidParameterValueException("There volume " + volume + " doesn't belong to " + "the virtual machine " + vm + " that has to be migrated");
                }
                volToPoolObjectMap.put(volume.getId(), pool.getId());
            }
        }
    }
    // Check if all the volumes are in the correct state.
    for (final VolumeVO volume : vmVolumes) {
        if (volume.getState() != Volume.State.Ready) {
            throw new CloudRuntimeException("Volume " + volume + " of the VM is not in Ready state. Cannot " + "migrate the vm with its volumes.");
        }
    }
    // Check max guest vm limit for the destinationHost.
    final HostVO destinationHostVO = _hostDao.findById(destinationHost.getId());
    if (_capacityMgr.checkIfHostReachMaxGuestLimit(destinationHostVO)) {
        throw new VirtualMachineMigrationException("Host name: " + destinationHost.getName() + ", hostId: " + destinationHost.getId() + " already has max running vms (count includes system VMs). Cannot" + " migrate to this host");
    }
    checkHostsDedication(vm, srcHostId, destinationHost.getId());
    _itMgr.migrateWithStorage(vm.getUuid(), srcHostId, destinationHost.getId(), volToPoolObjectMap);
    return _vmDao.findById(vm.getId());
}
Also used : HypervisorCapabilitiesVO(com.cloud.hypervisor.HypervisorCapabilitiesVO) Account(com.cloud.legacymodel.user.Account) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Host(com.cloud.legacymodel.dc.Host) HostVO(com.cloud.host.HostVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) StoragePoolVO(com.cloud.storage.datastore.db.StoragePoolVO) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) VirtualMachineMigrationException(com.cloud.legacymodel.exceptions.VirtualMachineMigrationException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ActionEvent(com.cloud.event.ActionEvent)

Example 23 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method createVirtualMachine.

@DB
private UserVm createVirtualMachine(final Zone zone, final ServiceOffering serviceOffering, final VirtualMachineTemplate tmplt, String hostName, final String displayName, final Account owner, final Long diskOfferingId, final Long diskSize, final List<NetworkVO> networkList, final String group, final HTTPMethod httpmethod, final String userData, final String sshKeyPair, final HypervisorType hypervisor, final Account caller, final Map<Long, IpAddresses> requestedIps, final IpAddresses defaultIps, final Boolean isDisplayVm, final String keyboard, final List<Long> affinityGroupIdList, final Map<String, String> customParameters, final String customId, final DiskControllerType diskControllerType, final Long bootMenuTimeout, MaintenancePolicy maintenancePolicy, OptimiseFor optimiseFor, String manufacturerString, String bootOrder) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException, StorageUnavailableException, ResourceAllocationException {
    _accountMgr.checkAccess(caller, null, true, owner);
    if (owner.getState() == Account.State.disabled) {
        throw new PermissionDeniedException("The owner of vm to deploy is disabled: " + owner);
    }
    final VMTemplateVO template = _templateDao.findById(tmplt.getId());
    if (template != null) {
        _templateDao.loadDetails(template);
    }
    if (optimiseFor == null) {
        if (template.getOptimiseFor() != null) {
            optimiseFor = template.getOptimiseFor();
        } else {
            optimiseFor = OptimiseFor.Generic;
        }
    }
    if (manufacturerString == null) {
        manufacturerString = template.getManufacturerString();
    }
    if (maintenancePolicy == null) {
        maintenancePolicy = template.getMaintenancePolicy();
    }
    Boolean macLarning = template.getMacLearning();
    String cpuFlags = template.getCpuFlags();
    final long accountId = owner.getId();
    assert !(requestedIps != null && (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null)) : "requestedIp list and defaultNetworkIp should never be " + "specified together";
    if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
        throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getId());
    }
    // check if zone is dedicated
    final DedicatedResourceVO dedicatedZone = _dedicatedDao.findByZoneId(zone.getId());
    if (dedicatedZone != null) {
        final DomainVO domain = _domainDao.findById(dedicatedZone.getDomainId());
        if (domain == null) {
            throw new CloudRuntimeException("Unable to find the domain " + zone.getDomainId() + " for the zone: " + zone);
        }
        // check that caller can operate with domain
        _configMgr.checkZoneAccess(caller, zone);
        // check that vm owner can create vm in the domain
        _configMgr.checkZoneAccess(owner, zone);
    }
    ServiceOfferingVO offering = _serviceOfferingDao.findById(serviceOffering.getId());
    // check if account/domain is with in resource limits to create a new vm
    final boolean isIso = ImageFormat.ISO == template.getFormat();
    long size = 0;
    // custom root disk size, resizes base template to larger size
    if (customParameters.containsKey("rootdisksize")) {
        final Long rootDiskSize = NumbersUtil.parseLong(customParameters.get("rootdisksize"), -1);
        if (rootDiskSize <= 0) {
            throw new InvalidParameterValueException("Root disk size should be a positive number.");
        }
        size = rootDiskSize * GB_TO_BYTES;
    }
    if (diskOfferingId != null) {
        final DiskOfferingVO diskOffering = _diskOfferingDao.findById(diskOfferingId);
        if (diskOffering != null && diskOffering.isCustomized()) {
            if (diskSize == null) {
                throw new InvalidParameterValueException("This disk offering requires a custom size specified");
            }
            final Long customDiskOfferingMaxSize = VolumeOrchestrationService.CustomDiskOfferingMaxSize.value();
            final Long customDiskOfferingMinSize = VolumeOrchestrationService.CustomDiskOfferingMinSize.value();
            if (diskSize < customDiskOfferingMinSize || diskSize > customDiskOfferingMaxSize) {
                throw new InvalidParameterValueException("VM Creation failed. Volume size: " + diskSize + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + " Min:" + customDiskOfferingMinSize);
            }
            size += diskSize * GB_TO_BYTES;
        }
        size += _diskOfferingDao.findById(diskOfferingId).getDiskSize();
    }
    resourceLimitCheck(owner, isDisplayVm, new Long(offering.getCpu()), new Long(offering.getRamSize()));
    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, isIso || diskOfferingId == null ? 1 : 2);
    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, size);
    // check that the affinity groups exist
    if (affinityGroupIdList != null) {
        for (final Long affinityGroupId : affinityGroupIdList) {
            final AffinityGroupVO ag = _affinityGroupDao.findById(affinityGroupId);
            if (ag == null) {
                throw new InvalidParameterValueException("Unable to find affinity group " + ag);
            } else if (!_affinityGroupService.isAffinityGroupProcessorAvailable(ag.getType())) {
                throw new InvalidParameterValueException("Affinity group type is not supported for group: " + ag + " ,type: " + ag.getType() + " , Please try again after removing the affinity group");
            } else {
                // verify permissions
                if (ag.getAclType() == ACLType.Domain) {
                    _accountMgr.checkAccess(caller, null, false, owner, ag);
                    // make sure the owner of these entities is same
                    if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                        if (!_affinityGroupService.isAffinityGroupAvailableInDomain(ag.getId(), owner.getDomainId())) {
                            throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain");
                        }
                    }
                } else {
                    _accountMgr.checkAccess(caller, null, true, owner, ag);
                    // make sure the owner of these entities is same
                    if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                        if (ag.getDomainId() != owner.getDomainId()) {
                            throw new PermissionDeniedException("Affinity Group " + ag + " does not belong to the VM's domain");
                        }
                    }
                }
            }
        }
    }
    final HypervisorType hypervisorType;
    if (template.getHypervisorType() == null || template.getHypervisorType() == HypervisorType.None) {
        if (hypervisor == null || hypervisor == HypervisorType.None) {
            throw new InvalidParameterValueException("hypervisor parameter is needed to deploy VM or the hypervisor parameter value passed is invalid");
        }
        hypervisorType = hypervisor;
    } else {
        if (hypervisor != null && hypervisor != HypervisorType.None && hypervisor != template.getHypervisorType()) {
            throw new InvalidParameterValueException("Hypervisor passed to the deployVm call, is different from the hypervisor type of the template");
        }
        hypervisorType = template.getHypervisorType();
    }
    // check if we have available pools for vm deployment
    final long availablePools = _storagePoolDao.countPoolsByStatus(StoragePoolStatus.Up);
    if (availablePools < 1) {
        throw new StorageUnavailableException("There are no available pools in the UP state for vm deployment", -1);
    }
    if (template.getTemplateType().equals(TemplateType.SYSTEM)) {
        throw new InvalidParameterValueException("Unable to use system template " + template.getId() + " to deploy a user vm");
    }
    final List<VMTemplateZoneVO> listZoneTemplate = _templateZoneDao.listByZoneTemplate(zone.getId(), template.getId());
    if (listZoneTemplate == null || listZoneTemplate.isEmpty()) {
        throw new InvalidParameterValueException("The template " + template.getId() + " is not available for use");
    }
    if (isIso && !template.isBootable()) {
        throw new InvalidParameterValueException("Installing from ISO requires an ISO that is bootable: " + template.getId());
    }
    // Check templates permissions
    _accountMgr.checkAccess(owner, AccessType.UseEntry, false, template);
    // check if the user data is correct
    validateUserData(userData, httpmethod);
    // Find an SSH public key corresponding to the key pair name, if one is
    // given
    String sshPublicKey = null;
    if (sshKeyPair != null && !sshKeyPair.equals("")) {
        final SSHKeyPair pair = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), sshKeyPair);
        if (pair == null) {
            throw new InvalidParameterValueException("A key pair with name '" + sshKeyPair + "' was not found.");
        }
        sshPublicKey = pair.getPublicKey();
    }
    final List<Pair<NetworkVO, NicProfile>> networks = new ArrayList<>();
    final LinkedHashMap<String, NicProfile> networkNicMap = new LinkedHashMap<>();
    short defaultNetworkNumber = 0;
    boolean vpcNetwork = false;
    for (final NetworkVO network : networkList) {
        if (network.getDataCenterId() != zone.getId()) {
            if (!network.isStrechedL2Network()) {
                throw new InvalidParameterValueException("Network id=" + network.getId() + " doesn't belong to zone " + zone.getId());
            }
            final NetworkOffering ntwkOffering = _networkOfferingDao.findById(network.getNetworkOfferingId());
            final Long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), ntwkOffering.getTags(), ntwkOffering.getTrafficType());
            if (physicalNetworkId == null) {
                throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
            }
            final String provider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.Connectivity);
            if (!_networkModel.isProviderEnabledInPhysicalNetwork(physicalNetworkId, provider)) {
                throw new InvalidParameterValueException("Network in which is VM getting deployed could not be" + " streched to the zone, as we could not find a valid physical network");
            }
        }
        // relax the check if the caller is admin account
        if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            if (!(network.getGuestType() == GuestType.Shared && network.getAclType() == ACLType.Domain) && !(network.getAclType() == ACLType.Account && network.getAccountId() == accountId)) {
                throw new InvalidParameterValueException("only shared network or isolated network with the same account_id can be added to vm");
            }
        }
        IpAddresses requestedIpPair = null;
        if (requestedIps != null && !requestedIps.isEmpty()) {
            requestedIpPair = requestedIps.get(network.getId());
        }
        if (requestedIpPair == null) {
            requestedIpPair = new IpAddresses(null, null);
        } else {
            _networkModel.checkRequestedIpAddresses(network.getId(), requestedIpPair);
        }
        NicProfile profile = new NicProfile(requestedIpPair.getIp4Address(), requestedIpPair.getIp6Address(), requestedIpPair.getMacAddress());
        if (defaultNetworkNumber == 0) {
            defaultNetworkNumber++;
            // if user requested specific ip for default network, add it
            if (defaultIps.getIp4Address() != null || defaultIps.getIp6Address() != null) {
                _networkModel.checkRequestedIpAddresses(network.getId(), defaultIps);
                profile = new NicProfile(defaultIps.getIp4Address(), defaultIps.getIp6Address());
            } else if (defaultIps.getMacAddress() != null) {
                profile = new NicProfile(null, null, defaultIps.getMacAddress());
            }
            profile.setDefaultNic(true);
            if (!_networkModel.areServicesSupportedInNetwork(network.getId(), new Service[] { Service.UserData })) {
                if (userData != null && !userData.isEmpty()) {
                    throw new InvalidParameterValueException("Unable to deploy VM as UserData is provided while deploying the VM, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
                if (sshPublicKey != null && !sshPublicKey.isEmpty()) {
                    throw new InvalidParameterValueException("Unable to deploy VM as SSH keypair is provided while deploying the VM, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
                if (template.getEnablePassword()) {
                    throw new InvalidParameterValueException("Unable to deploy VM as template " + template.getId() + " is password enabled, but there is no support for " + Network.Service.UserData.getName() + " service in the default network " + network.getId());
                }
            }
        }
        networks.add(new Pair<>(network, profile));
        networkNicMap.put(network.getUuid(), profile);
    }
    // gateway for the vm
    if (defaultNetworkNumber == 0) {
        throw new InvalidParameterValueException("At least 1 default network has to be specified for the vm");
    } else if (defaultNetworkNumber > 1) {
        throw new InvalidParameterValueException("Only 1 default network per vm is supported");
    }
    final long id = _vmDao.getNextInSequence(Long.class, "id");
    if (hostName != null) {
        // Check is hostName is RFC compliant
        checkNameForRFCCompliance(hostName);
    }
    final String instanceName;
    final String uuidName = _uuidMgr.generateUuid(UserVm.class, customId);
    if (hostName == null) {
        // Generate name using uuid and instance.name global config
        hostName = generateHostName(uuidName);
    }
    if (hostName != null) {
        // Check is hostName is RFC compliant
        checkNameForRFCCompliance(hostName);
    }
    instanceName = VirtualMachineName.getVmName(id, owner.getId(), _instance);
    // Check if VM with instanceName already exists.
    final VMInstanceVO vmObj = _vmInstanceDao.findVMByInstanceName(instanceName);
    if (vmObj != null && vmObj.getState() != VirtualMachine.State.Expunging) {
        throw new InvalidParameterValueException("There already exists a VM by the display name supplied");
    }
    checkIfHostNameUniqueInNtwkDomain(hostName, networkList);
    long userId = CallContext.current().getCallingUserId();
    if (CallContext.current().getCallingAccount().getId() != owner.getId()) {
        final List<UserVO> userVOs = _userDao.listByAccount(owner.getAccountId());
        if (!userVOs.isEmpty()) {
            userId = userVOs.get(0).getId();
        }
    }
    final UserVmVO vm = commitUserVm(zone, template, hostName, displayName, owner, diskOfferingId, diskSize, userData, caller, isDisplayVm, keyboard, accountId, userId, offering, isIso, sshPublicKey, networkNicMap, id, instanceName, uuidName, hypervisorType, customParameters, diskControllerType, manufacturerString, optimiseFor, macLarning, cpuFlags, maintenancePolicy, bootMenuTimeout, bootOrder);
    // Assign instance to the group
    try {
        if (group != null) {
            final boolean addToGroup = addInstanceToGroup(Long.valueOf(id), group);
            if (!addToGroup) {
                throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
            }
        }
    } catch (final Exception ex) {
        throw new CloudRuntimeException("Unable to assign Vm to the group " + group);
    }
    if (affinityGroupIdList != null && !affinityGroupIdList.isEmpty()) {
        _affinityGroupVMMapDao.updateMap(vm.getId(), affinityGroupIdList);
    }
    CallContext.current().putContextParameter(VirtualMachine.class, vm.getUuid());
    return vm;
}
Also used : VMTemplateZoneVO(com.cloud.storage.VMTemplateZoneVO) VMTemplateVO(com.cloud.storage.VMTemplateVO) ArrayList(java.util.ArrayList) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) LinkedHashMap(java.util.LinkedHashMap) StorageUnavailableException(com.cloud.legacymodel.exceptions.StorageUnavailableException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) DiskOfferingVO(com.cloud.storage.DiskOfferingVO) SSHKeyPair(com.cloud.legacymodel.user.SSHKeyPair) Pair(com.cloud.legacymodel.utils.Pair) AffinityGroupVO(com.cloud.affinity.AffinityGroupVO) SSHKeyPair(com.cloud.legacymodel.user.SSHKeyPair) NetworkVO(com.cloud.network.dao.NetworkVO) NetworkOffering(com.cloud.offering.NetworkOffering) AccountService(com.cloud.user.AccountService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Service(com.cloud.legacymodel.network.Network.Service) OrchestrationService(com.cloud.engine.service.api.OrchestrationService) ExecutorService(java.util.concurrent.ExecutorService) NetworkOrchestrationService(com.cloud.engine.orchestration.service.NetworkOrchestrationService) ManagementService(com.cloud.server.ManagementService) ResourceLimitService(com.cloud.user.ResourceLimitService) VolumeApiService(com.cloud.storage.VolumeApiService) AffinityGroupService(com.cloud.affinity.AffinityGroupService) VolumeOrchestrationService(com.cloud.engine.orchestration.service.VolumeOrchestrationService) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) OperationTimedoutException(com.cloud.legacymodel.exceptions.OperationTimedoutException) InsufficientAddressCapacityException(com.cloud.legacymodel.exceptions.InsufficientAddressCapacityException) VirtualMachineMigrationException(com.cloud.legacymodel.exceptions.VirtualMachineMigrationException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) ExecutionException(com.cloud.legacymodel.exceptions.ExecutionException) ResourceAllocationException(com.cloud.legacymodel.exceptions.ResourceAllocationException) CloudException(com.cloud.legacymodel.exceptions.CloudException) NoTransitionException(com.cloud.legacymodel.exceptions.NoTransitionException) InsufficientCapacityException(com.cloud.legacymodel.exceptions.InsufficientCapacityException) AgentUnavailableException(com.cloud.legacymodel.exceptions.AgentUnavailableException) ConfigurationException(javax.naming.ConfigurationException) StorageUnavailableException(com.cloud.legacymodel.exceptions.StorageUnavailableException) ResourceUnavailableException(com.cloud.legacymodel.exceptions.ResourceUnavailableException) ManagementServerException(com.cloud.legacymodel.exceptions.ManagementServerException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) HypervisorType(com.cloud.model.enumeration.HypervisorType) IpAddresses(com.cloud.legacymodel.network.Network.IpAddresses) DomainVO(com.cloud.domain.DomainVO) UserVO(com.cloud.user.UserVO) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) DB(com.cloud.utils.db.DB)

Example 24 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method updateUser.

@Override
@ActionEvent(eventType = EventTypes.EVENT_USER_UPDATE, eventDescription = "updating User")
public UserAccount updateUser(final Long userId, final String firstName, final String lastName, final String email, final String userName, final String password, final String apiKey, final String secretKey, final String timeZone) {
    // Input validation
    final UserVO user = _userDao.getUser(userId);
    if (user == null) {
        throw new InvalidParameterValueException("unable to find user by id");
    }
    if ((apiKey == null && secretKey != null) || (apiKey != null && secretKey == null)) {
        throw new InvalidParameterValueException("Please provide an userApiKey/userSecretKey pair");
    }
    // If the account is an admin type, return an error. We do not allow this
    final Account account = _accountDao.findById(user.getAccountId());
    if (account == null) {
        throw new InvalidParameterValueException("unable to find user account " + user.getAccountId());
    }
    // don't allow updating project account
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        throw new InvalidParameterValueException("unable to find user by id");
    }
    // don't allow updating system account
    if (account.getId() == Account.ACCOUNT_ID_SYSTEM) {
        throw new PermissionDeniedException("user id : " + userId + " is system account, update is not allowed");
    }
    checkAccess(CallContext.current().getCallingAccount(), AccessType.OperateEntry, true, account);
    if (firstName != null) {
        if (firstName.isEmpty()) {
            throw new InvalidParameterValueException("Firstname is empty");
        }
        user.setFirstname(firstName);
    }
    if (lastName != null) {
        if (lastName.isEmpty()) {
            throw new InvalidParameterValueException("Lastname is empty");
        }
        user.setLastname(lastName);
    }
    if (userName != null) {
        if (userName.isEmpty()) {
            throw new InvalidParameterValueException("Username is empty");
        }
        // don't allow to have same user names in the same domain
        final List<UserVO> duplicatedUsers = _userDao.findUsersByName(userName);
        for (final UserVO duplicatedUser : duplicatedUsers) {
            if (duplicatedUser.getId() != user.getId()) {
                final Account duplicatedUserAccount = _accountDao.findById(duplicatedUser.getAccountId());
                if (duplicatedUserAccount.getDomainId() == account.getDomainId()) {
                    throw new InvalidParameterValueException("User with name " + userName + " already exists in domain " + duplicatedUserAccount.getDomainId());
                }
            }
        }
        user.setUsername(userName);
    }
    if (password != null) {
        if (password.isEmpty()) {
            throw new InvalidParameterValueException("Password cannot be empty");
        }
        String encodedPassword = null;
        for (final Iterator<UserAuthenticator> en = _userPasswordEncoders.iterator(); en.hasNext(); ) {
            final UserAuthenticator authenticator = en.next();
            encodedPassword = authenticator.encode(password);
            if (encodedPassword != null) {
                break;
            }
        }
        if (encodedPassword == null) {
            throw new CloudRuntimeException("Failed to encode password");
        }
        user.setPassword(encodedPassword);
    }
    if (email != null) {
        user.setEmail(email);
    }
    if (timeZone != null) {
        user.setTimezone(timeZone);
    }
    if (apiKey != null) {
        user.setApiKey(apiKey);
    }
    if (secretKey != null) {
        user.setSecretKey(secretKey);
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("updating user with id: " + userId);
    }
    // check if the apiKey and secretKey are globally unique
    if (apiKey != null && secretKey != null) {
        final Pair<User, Account> apiKeyOwner = _accountDao.findUserAccountByApiKey(apiKey);
        if (apiKeyOwner != null) {
            final User usr = apiKeyOwner.first();
            if (usr.getId() != userId) {
                throw new InvalidParameterValueException("The api key:" + apiKey + " exists in the system for user id:" + userId + " ,please provide a unique key");
            }
        }
    }
    _userDao.update(userId, user);
    CallContext.current().putContextParameter(User.class, user.getUuid());
    return _userAccountDao.findById(userId);
}
Also used : UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) User(com.cloud.legacymodel.user.User) VpnUserVO(com.cloud.network.VpnUserVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) UserAuthenticator(com.cloud.server.auth.UserAuthenticator) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent)

Example 25 with PermissionDeniedException

use of com.cloud.legacymodel.exceptions.PermissionDeniedException in project cosmic by MissionCriticalCloud.

the class AccountManagerImpl method finalizeOwner.

@Override
public Account finalizeOwner(final Account caller, final String accountName, final Long domainId, final Long projectId) {
    // don't default the owner to the system account
    if (caller.getId() == Account.ACCOUNT_ID_SYSTEM && ((accountName == null || domainId == null) && projectId == null)) {
        throw new InvalidParameterValueException("Account and domainId are needed for resource creation");
    }
    // projectId and account/domainId can't be specified together
    if ((accountName != null && domainId != null) && projectId != null) {
        throw new InvalidParameterValueException("ProjectId and account/domainId can't be specified together");
    }
    if (projectId != null) {
        final Project project = _projectMgr.getProject(projectId);
        if (project == null) {
            throw new InvalidParameterValueException("Unable to find project by id=" + projectId);
        }
        if (!_projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) {
            throw new PermissionDeniedException("Account " + caller + " is unauthorised to use project id=" + projectId);
        }
        return getAccount(project.getProjectAccountId());
    }
    if (isAdmin(caller.getId()) && accountName != null && domainId != null) {
        final Domain domain = _domainMgr.getDomain(domainId);
        if (domain == null) {
            throw new InvalidParameterValueException("Unable to find the domain by id=" + domainId);
        }
        final Account owner = _accountDao.findActiveAccount(accountName, domainId);
        if (owner == null) {
            throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
        }
        checkAccess(caller, domain);
        return owner;
    } else if (!isAdmin(caller.getId()) && accountName != null && domainId != null) {
        if (!accountName.equals(caller.getAccountName()) || domainId.longValue() != caller.getDomainId()) {
            throw new PermissionDeniedException("Can't create/list resources for account " + accountName + " in domain " + domainId + ", permission denied");
        } else {
            return caller;
        }
    } else {
        if ((accountName == null && domainId != null) || (accountName != null && domainId == null)) {
            throw new InvalidParameterValueException("AccountName and domainId must be specified together");
        }
        // regular user can't create/list resources for other people
        return caller;
    }
}
Also used : Project(com.cloud.projects.Project) UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) Domain(com.cloud.legacymodel.domain.Domain)

Aggregations

PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)73 Account (com.cloud.legacymodel.user.Account)64 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)59 ActionEvent (com.cloud.event.ActionEvent)26 CloudRuntimeException (com.cloud.legacymodel.exceptions.CloudRuntimeException)25 ArrayList (java.util.ArrayList)14 UserAccount (com.cloud.legacymodel.user.UserAccount)13 DB (com.cloud.utils.db.DB)13 DataCenterVO (com.cloud.dc.DataCenterVO)11 HashMap (java.util.HashMap)11 DomainVO (com.cloud.domain.DomainVO)9 ResourceUnavailableException (com.cloud.legacymodel.exceptions.ResourceUnavailableException)9 Project (com.cloud.projects.Project)9 InsufficientCapacityException (com.cloud.legacymodel.exceptions.InsufficientCapacityException)8 Pair (com.cloud.legacymodel.utils.Pair)8 VMTemplateVO (com.cloud.storage.VMTemplateVO)8 TransactionStatus (com.cloud.utils.db.TransactionStatus)8 List (java.util.List)8 Domain (com.cloud.legacymodel.domain.Domain)7 VolumeVO (com.cloud.storage.VolumeVO)7