Search in sources :

Example 46 with PermissionDeniedException

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

the class VpcManagerImpl method createVpc.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VPC_CREATE, eventDescription = "creating vpc", create = true)
public Vpc createVpc(final long zoneId, final long vpcOffId, final long vpcOwnerId, final String vpcName, final String displayText, final String cidr, String networkDomain, final Boolean displayVpc, final String sourceNatList, final String syslogServerList, Long advertInterval, AdvertMethod advertMethod) throws ResourceAllocationException {
    final Account caller = CallContext.current().getCallingAccount();
    final Account owner = _accountMgr.getAccount(vpcOwnerId);
    // Verify that caller can perform actions in behalf of vpc owner
    _accountMgr.checkAccess(caller, null, false, owner);
    // check resource limit
    _resourceLimitMgr.checkResourceLimit(owner, ResourceType.vpc);
    // Validate vpc offering
    final VpcOfferingVO vpcOff = _vpcOffDao.findById(vpcOffId);
    if (vpcOff == null || vpcOff.getState() != State.Enabled) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find vpc offering in " + State.Enabled + " state by specified id");
        if (vpcOff == null) {
            ex.addProxyObject(String.valueOf(vpcOffId), "vpcOfferingId");
        } else {
            ex.addProxyObject(vpcOff.getUuid(), "vpcOfferingId");
        }
        throw ex;
    }
    // Validate zone
    final DataCenter zone = _entityMgr.findById(DataCenter.class, zoneId);
    if (zone == null) {
        throw new InvalidParameterValueException("Can't find zone by id specified");
    }
    if (AllocationState.Disabled == zone.getAllocationState() && !_accountMgr.isRootAdmin(caller.getId())) {
        // See DataCenterVO.java
        final PermissionDeniedException ex = new PermissionDeniedException("Cannot perform this operation since specified Zone is currently disabled");
        ex.addProxyObject(zone.getUuid(), "zoneId");
        throw ex;
    }
    if (networkDomain == null) {
        // 1) Get networkDomain from the corresponding account
        networkDomain = _ntwkModel.getAccountNetworkDomain(owner.getId(), zoneId);
        // global config variables
        if (networkDomain == null) {
            networkDomain = "cs" + Long.toHexString(owner.getId()) + NetworkOrchestrationService.GuestDomainSuffix.valueIn(zoneId);
        }
    }
    String unicastSubnet = _configDao.getValue(Config.RedundantRouterUnicastSubnet.key());
    if (unicastSubnet == null || unicastSubnet.isEmpty() || !NetUtils.isValidIp4Cidr(unicastSubnet)) {
        unicastSubnet = "100.100.0.0/24";
    }
    if (advertMethod == null) {
        try {
            String advertMethodConfigValue = _configDao.getValue(Config.RedundantRouterAdvertMethod.key());
            advertMethod = AdvertMethod.valueOf(advertMethodConfigValue);
        } catch (final IllegalArgumentException ex) {
            advertMethod = AdvertMethod.MULTICAST;
        }
    }
    if (advertInterval == null) {
        advertInterval = NumbersUtil.parseLong(_configDao.getValue(Config.RedundantRouterVrrpInterval.key()), 1);
    }
    final VpcVO vpc = new VpcVO(zoneId, vpcName, displayText, owner.getId(), owner.getDomainId(), vpcOffId, cidr, networkDomain, vpcOff.getRedundantRouter(), sourceNatList, syslogServerList, advertInterval, unicastSubnet, advertMethod);
    return createVpc(displayVpc, vpc);
}
Also used : Account(com.cloud.legacymodel.user.Account) DataCenter(com.cloud.legacymodel.dc.DataCenter) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent)

Example 47 with PermissionDeniedException

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

the class StaticRoleBasedAPIAccessChecker method checkAccess.

@Override
public boolean checkAccess(final User user, final String commandName) throws PermissionDeniedException {
    final Account account = _accountService.getAccount(user.getAccountId());
    if (account == null) {
        throw new PermissionDeniedException("The account id=" + user.getAccountId() + "for user id=" + user.getId() + "is null");
    }
    final RoleType roleType = _accountService.getRoleType(account);
    final boolean isAllowed = commandsPropertiesOverrides.contains(commandName) ? commandsPropertiesRoleBasedApisMap.get(roleType).contains(commandName) : annotationRoleBasedApisMap.get(roleType).contains(commandName);
    if (!isAllowed) {
        throw new PermissionDeniedException("The API does not exist or is blacklisted. Role type=" + roleType.toString() + " is not allowed to request the api: " + commandName);
    }
    return true;
}
Also used : Account(com.cloud.legacymodel.user.Account) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException)

Example 48 with PermissionDeniedException

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

the class AffinityGroupServiceImpl method updateVMAffinityGroups.

@Override
public UserVm updateVMAffinityGroups(final Long vmId, final List<Long> affinityGroupIds) {
    // Verify input parameters
    final UserVmVO vmInstance = _userVmDao.findById(vmId);
    if (vmInstance == null) {
        throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
    }
    final Account caller = CallContext.current().getCallingAccount();
    final Account owner = _accountMgr.getAccount(vmInstance.getAccountId());
    // check that the affinity groups exist
    for (final Long affinityGroupId : affinityGroupIds) {
        final AffinityGroupVO AffinityGroupVO = _affinityGroupDao.findById(affinityGroupId);
        if (AffinityGroupVO == null) {
            throw new InvalidParameterValueException("Unable to find affinity group by id " + affinityGroupId);
        } else {
            // verify permissions (same as when deploying VM)
            _accountMgr.checkAccess(caller, null, false, owner, AffinityGroupVO);
            // Only Explicit Dedication can be handled in non-Stopped state
            if ("ExplicitDedication".equals(AffinityGroupVO.getType())) {
                // Check if VM is currently running on host Explicitly Dedicated to this domain
                Boolean VmRunsOnDedicatedHost = false;
                final Pair<List<DedicatedResourceVO>, Integer> result = _dedicatedDao.searchDedicatedHosts(vmInstance.getHostId(), vmInstance.getDomainId(), null, affinityGroupId);
                final List<DedicatedResourceVO> DedicatedResourceList = result.first();
                for (final DedicatedResourceVO dedicatedResourceVO : DedicatedResourceList) {
                    if (dedicatedResourceVO.getHostId() != null && dedicatedResourceVO.getHostId().equals(vmInstance.getHostId())) {
                        VmRunsOnDedicatedHost = true;
                    }
                }
                if (!VmRunsOnDedicatedHost && !State.Stopped.equals(vmInstance.getState())) {
                    throw new InvalidParameterValueException("Unable update Explicit Dedication affinity groups of the virtual machine " + vmInstance.toString() + " " + "in state " + vmInstance.getState() + "; make sure the virtual machine is either stopped or running on a host that is part of the " + "Explicit Dedication Affinity Group.");
                }
            } else {
                if (!State.Stopped.equals(vmInstance.getState())) {
                    throw new InvalidParameterValueException("Unable update affinity groups of the virtual machine " + vmInstance.toString() + " " + "in state " + vmInstance.getState() + "; make sure the virtual machine is stopped and not in an error state before updating.");
                }
            }
            // owner of these entities is same
            if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || _accountMgr.isRootAdmin(caller.getId())) {
                if (!_affinityGroupService.isAffinityGroupAvailableInDomain(AffinityGroupVO.getId(), owner.getDomainId())) {
                    throw new PermissionDeniedException("Affinity Group " + AffinityGroupVO + " does not belong to the VM's domain");
                }
            }
        }
    }
    _affinityGroupVMMapDao.updateMap(vmId, affinityGroupIds);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Updated VM :" + vmId + " affinity groups to =" + affinityGroupIds);
    }
    // APIResponseHelper will pull out the updated affinitygroups.
    return vmInstance;
}
Also used : Account(com.cloud.legacymodel.user.Account) UserVmVO(com.cloud.vm.UserVmVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) List(java.util.List) ArrayList(java.util.ArrayList) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO)

Example 49 with PermissionDeniedException

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

the class VolumeApiServiceImpl method allocSnapshotForVm.

@Override
public Snapshot allocSnapshotForVm(final Long vmId, final Long volumeId, final String snapshotName) throws ResourceAllocationException {
    final Account caller = CallContext.current().getCallingAccount();
    final VMInstanceVO vm = this._vmInstanceDao.findById(vmId);
    if (vm == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to vm:" + vmId + " doesn't exist");
    }
    this._accountMgr.checkAccess(caller, null, true, vm);
    final VolumeInfo volume = this.volFactory.getVolume(volumeId);
    if (volume == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
    }
    this._accountMgr.checkAccess(caller, null, true, volume);
    final VirtualMachine attachVM = volume.getAttachedVM();
    if (attachVM == null || attachVM.getId() != vm.getId()) {
        throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't attach to vm :" + vm);
    }
    final DataCenter zone = this._dcDao.findById(volume.getDataCenterId());
    if (zone == null) {
        throw new InvalidParameterValueException("Can't find zone by id " + volume.getDataCenterId());
    }
    if (AllocationState.Disabled == zone.getAllocationState() && !this._accountMgr.isRootAdmin(caller.getId())) {
        throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zone.getName());
    }
    if (volume.getState() != Volume.State.Ready) {
        throw new InvalidParameterValueException("VolumeId: " + volumeId + " is not in " + Volume.State.Ready + " state but " + volume.getState() + ". Cannot take snapshot.");
    }
    if (volume.getTemplateId() != null) {
        final VMTemplateVO template = this._templateDao.findById(volume.getTemplateId());
        if (template != null && template.getTemplateType() == TemplateType.SYSTEM) {
            throw new InvalidParameterValueException("VolumeId: " + volumeId + " is for System VM , Creating snapshot against System VM volumes is not supported");
        }
    }
    final StoragePool storagePool = (StoragePool) volume.getDataStore();
    if (storagePool == null) {
        throw new InvalidParameterValueException("VolumeId: " + volumeId + " please attach this volume to a VM before create snapshot for it");
    }
    return this.snapshotMgr.allocSnapshot(volumeId, Snapshot.MANUAL_POLICY_ID, snapshotName, true);
}
Also used : Account(com.cloud.legacymodel.user.Account) DataCenter(com.cloud.legacymodel.dc.DataCenter) StoragePool(com.cloud.legacymodel.storage.StoragePool) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) VMInstanceVO(com.cloud.vm.VMInstanceVO) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) VirtualMachine(com.cloud.legacymodel.vm.VirtualMachine)

Example 50 with PermissionDeniedException

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

the class VolumeApiServiceImpl method allocVolume.

/*
     * Just allocate a volume in the database, don't send the createvolume cmd
     * to hypervisor. The volume will be finally created only when it's attached
     * to a VM.
     */
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_CREATE, eventDescription = "creating volume", create = true)
public VolumeVO allocVolume(final CreateVolumeCmd cmd) throws ResourceAllocationException {
    // FIXME: some of the scheduled event stuff might be missing here...
    final Account caller = CallContext.current().getCallingAccount();
    final long ownerId = cmd.getEntityOwnerId();
    final Account owner = this._accountMgr.getActiveAccountById(ownerId);
    Boolean displayVolume = cmd.getDisplayVolume();
    // permission check
    this._accountMgr.checkAccess(caller, null, true, this._accountMgr.getActiveAccountById(ownerId));
    if (displayVolume == null) {
        displayVolume = true;
    } else {
        if (!this._accountMgr.isRootAdmin(caller.getId())) {
            throw new PermissionDeniedException("Cannot update parameter displayvolume, only admin permitted ");
        }
    }
    // Check that the resource limit for volumes won't be exceeded
    this._resourceLimitMgr.checkResourceLimit(owner, ResourceType.volume, displayVolume);
    Long zoneId = cmd.getZoneId();
    final Long diskOfferingId;
    final DiskOfferingVO diskOffering;
    final StorageProvisioningType provisioningType;
    Long size;
    Long minIops = null;
    Long maxIops = null;
    // Volume VO used for extracting the source template id
    VolumeVO parentVolume = null;
    // validate input parameters before creating the volume
    if (cmd.getSnapshotId() == null && cmd.getDiskOfferingId() == null || cmd.getSnapshotId() != null && cmd.getDiskOfferingId() != null) {
        throw new InvalidParameterValueException("Either disk Offering Id or snapshot Id must be passed whilst creating volume");
    }
    if (cmd.getSnapshotId() == null) {
        // create a new volume
        diskOfferingId = cmd.getDiskOfferingId();
        size = cmd.getSize();
        final Long sizeInGB = size;
        if (size != null) {
            if (size > 0) {
                // user specify size in GB
                size = size * 1024 * 1024 * 1024;
            } else {
                throw new InvalidParameterValueException("Disk size must be larger than 0");
            }
        }
        // Check that the the disk offering is specified
        diskOffering = this._diskOfferingDao.findById(diskOfferingId);
        if (diskOffering == null || diskOffering.getRemoved() != null || !DiskOfferingVO.Type.Disk.equals(diskOffering.getType())) {
            throw new InvalidParameterValueException("Please specify a valid disk offering.");
        }
        if (diskOffering.isCustomized()) {
            if (size == null) {
                throw new InvalidParameterValueException("This disk offering requires a custom size specified");
            }
            final Long customDiskOfferingMaxSize = this._volumeMgr.CustomDiskOfferingMaxSize.value();
            final Long customDiskOfferingMinSize = this._volumeMgr.CustomDiskOfferingMinSize.value();
            if (sizeInGB < customDiskOfferingMinSize || sizeInGB > customDiskOfferingMaxSize) {
                throw new InvalidParameterValueException("Volume size: " + sizeInGB + "GB is out of allowed range. Max: " + customDiskOfferingMaxSize + " Min:" + customDiskOfferingMinSize);
            }
        }
        if (!diskOffering.isCustomized() && size != null) {
            throw new InvalidParameterValueException("This disk offering does not allow custom size");
        }
        if (diskOffering.getDomainId() == null) {
        // do nothing as offering is public
        } else {
            this._configMgr.checkDiskOfferingAccess(caller, diskOffering);
        }
        if (diskOffering.getDiskSize() > 0) {
            size = diskOffering.getDiskSize();
        }
        final Boolean isCustomizedIops = diskOffering.isCustomizedIops();
        if (isCustomizedIops != null) {
            if (isCustomizedIops) {
                minIops = cmd.getMinIops();
                maxIops = cmd.getMaxIops();
                if (minIops == null && maxIops == null) {
                    minIops = 0L;
                    maxIops = 0L;
                } else {
                    if (minIops == null || minIops <= 0) {
                        throw new InvalidParameterValueException("The min IOPS must be greater than 0.");
                    }
                    if (maxIops == null) {
                        maxIops = 0L;
                    }
                    if (minIops > maxIops) {
                        throw new InvalidParameterValueException("The min IOPS must be less than or equal to the max IOPS.");
                    }
                }
            } else {
                minIops = diskOffering.getMinIops();
                maxIops = diskOffering.getMaxIops();
            }
        }
        provisioningType = diskOffering.getProvisioningType();
        if (!validateVolumeSizeRange(size)) {
            // for validation
            throw new InvalidParameterValueException("Invalid size for custom volume creation: " + size + " ,max volume size is:" + this._maxVolumeSizeInGb);
        }
    } else {
        // create volume from snapshot
        final Long snapshotId = cmd.getSnapshotId();
        final SnapshotVO snapshotCheck = this._snapshotDao.findById(snapshotId);
        if (snapshotCheck == null) {
            throw new InvalidParameterValueException("unable to find a snapshot with id " + snapshotId);
        }
        if (snapshotCheck.getState() != Snapshot.State.BackedUp) {
            throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp + " state yet and can't be used for volume " + "creation");
        }
        parentVolume = this._volsDao.findByIdIncludingRemoved(snapshotCheck.getVolumeId());
        diskOfferingId = snapshotCheck.getDiskOfferingId();
        diskOffering = this._diskOfferingDao.findById(diskOfferingId);
        if (zoneId == null) {
            // if zoneId is not provided, we default to create volume in the same zone as the snapshot zone.
            zoneId = snapshotCheck.getDataCenterId();
        }
        // ; disk offering is used for tags
        size = snapshotCheck.getSize();
        // purposes
        minIops = snapshotCheck.getMinIops();
        maxIops = snapshotCheck.getMaxIops();
        provisioningType = diskOffering.getProvisioningType();
        // check snapshot permissions
        this._accountMgr.checkAccess(caller, null, true, snapshotCheck);
        // one step operation - create volume in VM's cluster and attach it
        // to the VM
        final Long vmId = cmd.getVirtualMachineId();
        if (vmId != null) {
            // Check that the virtual machine ID is valid and it's a user vm
            final UserVmVO vm = this._userVmDao.findById(vmId);
            if (vm == null || vm.getType() != VirtualMachineType.User) {
                throw new InvalidParameterValueException("Please specify a valid User VM.");
            }
            // Check that the VM is in the correct state
            if (vm.getState() != State.Running && vm.getState() != State.Stopped) {
                throw new InvalidParameterValueException("Please specify a VM that is either running or stopped.");
            }
            // permission check
            this._accountMgr.checkAccess(caller, null, false, vm);
        }
    }
    // Check that the resource limit for primary storage won't be exceeded
    this._resourceLimitMgr.checkResourceLimit(owner, ResourceType.primary_storage, displayVolume, new Long(size));
    // Verify that zone exists
    final DataCenterVO zone = this._dcDao.findById(zoneId);
    if (zone == null) {
        throw new InvalidParameterValueException("Unable to find zone by id " + zoneId);
    }
    // Check if zone is disabled
    if (AllocationState.Disabled == zone.getAllocationState() && !this._accountMgr.isRootAdmin(caller.getId())) {
        throw new PermissionDeniedException("Cannot perform this operation, Zone is currently disabled: " + zoneId);
    }
    final String userSpecifiedName = getVolumeNameFromCommand(cmd);
    DiskControllerType diskControllerType = getDiskControllerType();
    if (cmd.getDiskController() != null) {
        diskControllerType = DiskControllerType.valueOf(cmd.getDiskController().toUpperCase());
    }
    ImageFormat fileFormat = ImageFormat.QCOW2;
    if (cmd.getFileFormat() != null) {
        fileFormat = ImageFormat.valueOf(cmd.getFileFormat().toUpperCase());
    }
    return commitVolume(cmd, caller, owner, displayVolume, zoneId, diskOfferingId, provisioningType, size, minIops, maxIops, parentVolume, userSpecifiedName, this._uuidMgr.generateUuid(Volume.class, cmd.getCustomId()), diskControllerType, fileFormat);
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.legacymodel.user.Account) UserVmVO(com.cloud.vm.UserVmVO) StorageProvisioningType(com.cloud.model.enumeration.StorageProvisioningType) ImageFormat(com.cloud.model.enumeration.ImageFormat) DiskControllerType(com.cloud.model.enumeration.DiskControllerType) VMSnapshotVO(com.cloud.vm.snapshot.VMSnapshotVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Volume(com.cloud.legacymodel.storage.Volume) VmWorkDetachVolume(com.cloud.vm.VmWorkDetachVolume) VmWorkMigrateVolume(com.cloud.vm.VmWorkMigrateVolume) VmWorkResizeVolume(com.cloud.vm.VmWorkResizeVolume) VmWorkAttachVolume(com.cloud.vm.VmWorkAttachVolume) VmWorkExtractVolume(com.cloud.vm.VmWorkExtractVolume) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

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