Search in sources :

Example 51 with PermissionDeniedException

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

the class VolumeApiServiceImpl method allocSnapshot.

@Override
@ActionEvent(eventType = EventTypes.EVENT_SNAPSHOT_CREATE, eventDescription = "allocating snapshot", create = true)
public Snapshot allocSnapshot(final Long volumeId, final Long policyId, final String snapshotName) throws ResourceAllocationException {
    final Account caller = CallContext.current().getCallingAccount();
    final VolumeInfo volume = this.volFactory.getVolume(volumeId);
    if (volume == null) {
        throw new InvalidParameterValueException("Creating snapshot failed due to volume:" + volumeId + " doesn't exist");
    }
    final DataCenter zone = this._dcDao.findById(volume.getDataCenterId());
    if (zone == null) {
        throw new InvalidParameterValueException("Can't find zone by id " + volume.getDataCenterId());
    }
    if (volume.getInstanceId() != null) {
        // Check that Vm to which this volume is attached does not have VM Snapshots
        if (this._vmSnapshotDao.findByVm(volume.getInstanceId()).size() > 0) {
            throw new InvalidParameterValueException("Volume snapshot is not allowed, please detach it from VM with VM Snapshots");
        }
    }
    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 (ImageFormat.DIR.equals(volume.getFormat())) {
        throw new InvalidParameterValueException("Snapshot not supported for volume:" + volumeId);
    }
    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, policyId, snapshotName, false);
}
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) VolumeInfo(com.cloud.engine.subsystem.api.storage.VolumeInfo) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent)

Example 52 with PermissionDeniedException

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

the class VolumeApiServiceImpl method validateVolume.

private boolean validateVolume(final Account caller, final long ownerId, final Long zoneId, final String volumeName, final String url, final String format, final Long diskOfferingId) throws ResourceAllocationException {
    // permission check
    final Account volumeOwner = this._accountMgr.getActiveAccountById(ownerId);
    this._accountMgr.checkAccess(caller, null, true, volumeOwner);
    // Check that the resource limit for volumes won't be exceeded
    this._resourceLimitMgr.checkResourceLimit(volumeOwner, ResourceType.volume);
    // 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);
    }
    // validating the url only when url is not null. url can be null incase of form based post upload
    if (url != null) {
        if (url.toLowerCase().contains("file://")) {
            throw new InvalidParameterValueException("File:// type urls are currently unsupported");
        }
        UriUtils.validateUrl(format, url);
        // check URL existence
        UriUtils.checkUrlExistence(url);
        // Check that the resource limit for secondary storage won't be exceeded
        this._resourceLimitMgr.checkResourceLimit(this._accountMgr.getAccount(ownerId), ResourceType.secondary_storage, UriUtils.getRemoteSize(url));
    } else {
        this._resourceLimitMgr.checkResourceLimit(this._accountMgr.getAccount(ownerId), ResourceType.secondary_storage);
    }
    try {
        ImageFormat.valueOf(format.toUpperCase());
    } catch (final IllegalArgumentException e) {
        s_logger.debug("ImageFormat IllegalArgumentException: " + e.getMessage());
        throw new IllegalArgumentException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
    }
    // Check that the the disk offering specified is valid
    if (diskOfferingId != null) {
        final DiskOfferingVO 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()) {
            throw new InvalidParameterValueException("Please specify a custom sized disk offering.");
        }
        if (diskOffering.getDomainId() == null) {
        // do nothing as offering is public
        } else {
            this._configMgr.checkDiskOfferingAccess(volumeOwner, diskOffering);
        }
    }
    return false;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.legacymodel.user.Account) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException)

Example 53 with PermissionDeniedException

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

the class VolumeApiServiceImpl method extractVolume.

@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_EXTRACT, eventDescription = "extracting volume", async = true)
public String extractVolume(final ExtractVolumeCmd cmd) {
    final Long volumeId = cmd.getId();
    final Long zoneId = cmd.getZoneId();
    final String mode = cmd.getMode();
    final Account account = CallContext.current().getCallingAccount();
    if (!this._accountMgr.isRootAdmin(account.getId()) && ApiDBUtils.isExtractionDisabled()) {
        throw new PermissionDeniedException("Extraction has been disabled by admin");
    }
    final VolumeVO volume = this._volsDao.findById(volumeId);
    if (volume == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId");
        ex.addProxyObject(volumeId.toString(), "volumeId");
        throw ex;
    }
    // perform permission check
    this._accountMgr.checkAccess(account, null, true, volume);
    if (this._dcDao.findById(zoneId) == null) {
        throw new InvalidParameterValueException("Please specify a valid zone.");
    }
    if (volume.getPoolId() == null) {
        throw new InvalidParameterValueException("The volume doesnt belong to a storage pool so cant extract it");
    }
    // instance is stopped
    if (volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) {
        s_logger.debug("Invalid state of the volume with ID: " + volumeId + ". It should be either detached or the VM should be in stopped state.");
        final PermissionDeniedException ex = new PermissionDeniedException("Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state.");
        ex.addProxyObject(volume.getUuid(), "volumeId");
        throw ex;
    }
    if (volume.getVolumeType() != VolumeType.DATADISK) {
        // Datadisk dont have any template dependence.
        final VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
        if (template != null) {
            // For ISO based volumes template = null and
            // we allow extraction of all ISO based
            // volumes
            final boolean isExtractable = template.isExtractable() && template.getTemplateType() != TemplateType.SYSTEM;
            if (!isExtractable && account != null && !this._accountMgr.isRootAdmin(account.getId())) {
                // Global admins are always allowed to extract
                final PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted");
                ex.addProxyObject(volume.getUuid(), "volumeId");
                throw ex;
            }
        }
    }
    if (mode == null || !mode.equals(Upload.Mode.FTP_UPLOAD.toString()) && !mode.equals(Upload.Mode.HTTP_DOWNLOAD.toString())) {
        throw new InvalidParameterValueException("Please specify a valid extract Mode ");
    }
    // Check if the url already exists
    final VolumeDataStoreVO volumeStoreRef = this._volumeStoreDao.findByVolume(volumeId);
    if (volumeStoreRef != null && volumeStoreRef.getExtractUrl() != null) {
        return volumeStoreRef.getExtractUrl();
    }
    VMInstanceVO vm = null;
    if (volume.getInstanceId() != null) {
        vm = this._vmInstanceDao.findById(volume.getInstanceId());
    }
    if (vm != null) {
        // serialize VM operation
        final AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
        if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
            // avoid re-entrance
            final VmWorkJobVO placeHolder;
            placeHolder = createPlaceHolderWork(vm.getId());
            try {
                return orchestrateExtractVolume(volume.getId(), zoneId);
            } finally {
                this._workJobDao.expunge(placeHolder.getId());
            }
        } else {
            final Outcome<String> outcome = extractVolumeThroughJobQueue(vm.getId(), volume.getId(), zoneId);
            try {
                outcome.get();
            } catch (final InterruptedException e) {
                throw new RuntimeException("Operation is interrupted", e);
            } catch (final java.util.concurrent.ExecutionException e) {
                throw new RuntimeException("Execution excetion", e);
            }
            final Object jobResult = this._jobMgr.unmarshallResultObject(outcome.getJob());
            if (jobResult != null) {
                if (jobResult instanceof ConcurrentOperationException) {
                    throw (ConcurrentOperationException) jobResult;
                } else if (jobResult instanceof RuntimeException) {
                    throw (RuntimeException) jobResult;
                } else if (jobResult instanceof Throwable) {
                    throw new RuntimeException("Unexpected exception", (Throwable) jobResult);
                }
            }
            // retrieve the entity url from job result
            if (jobResult != null && jobResult instanceof String) {
                return (String) jobResult;
            }
            return null;
        }
    }
    return orchestrateExtractVolume(volume.getId(), zoneId);
}
Also used : Account(com.cloud.legacymodel.user.Account) AsyncJobExecutionContext(com.cloud.framework.jobs.AsyncJobExecutionContext) VMInstanceVO(com.cloud.vm.VMInstanceVO) ConcurrentOperationException(com.cloud.legacymodel.exceptions.ConcurrentOperationException) VmWorkJobVO(com.cloud.framework.jobs.impl.VmWorkJobVO) ExecutionException(java.util.concurrent.ExecutionException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) VolumeDataStoreVO(com.cloud.storage.datastore.db.VolumeDataStoreVO) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) DataObject(com.cloud.engine.subsystem.api.storage.DataObject) ActionEvent(com.cloud.event.ActionEvent)

Example 54 with PermissionDeniedException

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

the class TemplateManagerImpl method createPrivateTemplateRecord.

@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", create = true)
public VMTemplateVO createPrivateTemplateRecord(final CreateTemplateCmd cmd, final Account templateOwner) throws ResourceAllocationException {
    final Account caller = CallContext.current().getCallingAccount();
    final boolean isAdmin = this._accountMgr.isAdmin(caller.getId());
    this._accountMgr.checkAccess(caller, null, true, templateOwner);
    final String name = cmd.getTemplateName();
    if (name == null || name.length() > 32) {
        throw new InvalidParameterValueException("Template name cannot be null and should be less than 32 characters");
    }
    if (cmd.getTemplateTag() != null) {
        if (!this._accountService.isRootAdmin(caller.getId())) {
            throw new PermissionDeniedException("Parameter templatetag can only be specified by a Root Admin, permission denied");
        }
    }
    // do some parameter defaulting
    final Integer bits = cmd.getBits();
    final Boolean passwordEnabled = cmd.isPasswordEnabled();
    Boolean isPublic = cmd.isPublic();
    Boolean featured = cmd.isFeatured();
    final int bitsValue = bits == null ? 64 : bits;
    final boolean passwordEnabledValue = passwordEnabled != null && passwordEnabled;
    if (isPublic == null) {
        isPublic = Boolean.FALSE;
    }
    final boolean isDynamicScalingEnabled = cmd.isDynamicallyScalable();
    // check whether template owner can create public templates
    final boolean allowPublicUserTemplates = AllowPublicUserTemplates.valueIn(templateOwner.getId());
    if (!isAdmin && !allowPublicUserTemplates && isPublic) {
        throw new PermissionDeniedException("Failed to create template " + name + ", only private templates can be created.");
    }
    final Long volumeId = cmd.getVolumeId();
    final Long snapshotId = cmd.getSnapshotId();
    if (volumeId == null && snapshotId == null) {
        throw new InvalidParameterValueException("Failed to create private template record, neither volume ID nor snapshot ID were specified.");
    }
    if (volumeId != null && snapshotId != null) {
        throw new InvalidParameterValueException("Failed to create private template record, please specify only one of volume ID (" + volumeId + ") and snapshot ID (" + snapshotId + ")");
    }
    HypervisorType hyperType;
    final VolumeVO volume;
    SnapshotVO snapshot = null;
    final VMTemplateVO privateTemplate;
    if (volumeId != null) {
        // create template from volume
        volume = this._volumeDao.findById(volumeId);
        if (volume == null) {
            throw new InvalidParameterValueException("Failed to create private template record, unable to find volume " + volumeId);
        }
        // check permissions
        this._accountMgr.checkAccess(caller, null, true, volume);
        // created
        if (!this._volumeMgr.volumeInactive(volume)) {
            final String msg = "Unable to create private template for volume: " + volume.getName() + "; volume is detached or attached to a Running VM";
            if (s_logger.isInfoEnabled()) {
                s_logger.info(msg);
            }
            throw new CloudRuntimeException(msg);
        }
        hyperType = this._volumeDao.getHypervisorType(volumeId);
        // Try to find a better one than None
        if (hyperType == HypervisorType.None) {
            try {
                final String hypers = _configDao.getValue(Config.HypervisorList.key());
                final String[] hypervisors = hypers.split(",");
                final String defaultHyper = hypervisors[0];
                hyperType = HypervisorType.valueOf(defaultHyper);
            } catch (IllegalArgumentException e) {
                s_logger.debug("Unable to get hypervisor from global settings");
                hyperType = HypervisorType.None;
            }
        }
    } else {
        // create template from snapshot
        snapshot = this._snapshotDao.findById(snapshotId);
        if (snapshot == null) {
            throw new InvalidParameterValueException("Failed to create private template record, unable to find snapshot " + snapshotId);
        }
        // Volume could be removed so find including removed to record source template id.
        volume = this._volumeDao.findByIdIncludingRemoved(snapshot.getVolumeId());
        // check permissions
        this._accountMgr.checkAccess(caller, null, true, snapshot);
        if (snapshot.getState() != Snapshot.State.BackedUp) {
            throw new InvalidParameterValueException("Snapshot id=" + snapshotId + " is not in " + Snapshot.State.BackedUp + " state yet and can't be used for template creation");
        }
        /*
             * // bug #11428. Operation not supported if vmware and snapshots
             * parent volume = ROOT if(snapshot.getHypervisorType() ==
             * HypervisorType.VMware && snapshotVolume.getVolumeType() ==
             * Type.DATADISK){ throw new UnsupportedServiceException(
             * "operation not supported, snapshot with id " + snapshotId +
             * " is created from Data Disk"); }
             */
        hyperType = snapshot.getHypervisorType();
    }
    this._resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);
    this._resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.secondary_storage, volume != null ? volume.getSize() : snapshot.getSize());
    if (!isAdmin || featured == null) {
        featured = Boolean.FALSE;
    }
    final Long guestOSId = cmd.getOsTypeId();
    final GuestOSVO guestOS = this._guestOSDao.findById(guestOSId);
    if (guestOS == null) {
        throw new InvalidParameterValueException("GuestOS with ID: " + guestOSId + " does not exist.");
    }
    final Long nextTemplateId = this._tmpltDao.getNextInSequence(Long.class, "id");
    final String description = cmd.getDisplayText();
    boolean isExtractable = false;
    Long sourceTemplateId = null;
    if (volume != null) {
        final VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
        isExtractable = template != null && template.isExtractable() && template.getTemplateType() != TemplateType.SYSTEM;
        if (volume.getIsoId() != null && volume.getIsoId() != 0) {
            sourceTemplateId = volume.getIsoId();
        } else if (volume.getTemplateId() != null) {
            sourceTemplateId = volume.getTemplateId();
        }
    }
    final String templateTag = cmd.getTemplateTag();
    if (templateTag != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Adding template tag: " + templateTag);
        }
    }
    // if specified from the API, use that one
    if (cmd.getHypervisor() != null) {
        hyperType = HypervisorType.getType(cmd.getHypervisor());
    }
    privateTemplate = new VMTemplateVO(nextTemplateId, name, ImageFormat.RAW, isPublic, featured, isExtractable, TemplateType.USER, null, bitsValue, templateOwner.getId(), null, description, passwordEnabledValue, guestOS.getId(), true, hyperType, templateTag, cmd.getDetails(), false, isDynamicScalingEnabled);
    if (sourceTemplateId != null) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("This template is getting created from other template, setting source template Id to: " + sourceTemplateId);
        }
    }
    // for region wide storage, set cross zones flag
    final List<ImageStoreVO> stores = this._imgStoreDao.findRegionImageStores();
    if (stores.size() > 0) {
        privateTemplate.setCrossZones(true);
    }
    privateTemplate.setSourceTemplateId(sourceTemplateId);
    final VMTemplateVO template = this._tmpltDao.persist(privateTemplate);
    // Increment the number of templates
    if (template != null) {
        final Map<String, String> details = new HashMap<>();
        if (volume != null) {
            final Long vmId = volume.getInstanceId();
            if (vmId != null) {
                final UserVmVO userVm = this._userVmDao.findById(vmId);
                if (userVm != null) {
                    this._userVmDao.loadDetails(userVm);
                    details.putAll(userVm.getDetails());
                }
            }
        }
        if (cmd.getDetails() != null) {
            // new password will be generated during vm deployment from password enabled template
            details.remove("Encrypted.Password");
            details.putAll(cmd.getDetails());
        }
        if (!details.isEmpty()) {
            privateTemplate.setDetails(details);
            this._tmpltDao.saveDetails(privateTemplate);
        }
        this._resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.template);
        this._resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.secondary_storage, new Long(volume != null ? volume.getSize() : snapshot.getSize()));
    }
    if (template != null) {
        return template;
    } else {
        throw new CloudRuntimeException("Failed to create a template");
    }
}
Also used : Account(com.cloud.legacymodel.user.Account) UserVmVO(com.cloud.vm.UserVmVO) HashMap(java.util.HashMap) VMTemplateVO(com.cloud.storage.VMTemplateVO) GuestOSVO(com.cloud.storage.GuestOSVO) EndPoint(com.cloud.engine.subsystem.api.storage.EndPoint) HypervisorType(com.cloud.model.enumeration.HypervisorType) SnapshotVO(com.cloud.storage.SnapshotVO) VolumeVO(com.cloud.storage.VolumeVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) ImageStoreVO(com.cloud.storage.datastore.db.ImageStoreVO) ActionEvent(com.cloud.event.ActionEvent)

Example 55 with PermissionDeniedException

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

the class TemplateManagerImpl method registerTemplate.

@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template")
public VirtualMachineTemplate registerTemplate(final RegisterTemplateCmd cmd) throws URISyntaxException, ResourceAllocationException {
    final Account account = CallContext.current().getCallingAccount();
    if (cmd.getTemplateTag() != null) {
        if (!this._accountService.isRootAdmin(account.getId())) {
            throw new PermissionDeniedException("Parameter templatetag can only be specified by a Root Admin, permission denied");
        }
    }
    if (cmd.isRoutingType() != null) {
        if (!this._accountService.isRootAdmin(account.getId())) {
            throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied");
        }
    }
    final TemplateAdapter adapter = getAdapter(HypervisorType.getType(cmd.getHypervisor()));
    final TemplateProfile profile = adapter.prepare(cmd);
    final VMTemplateVO template = adapter.create(profile);
    if (template != null) {
        return template;
    } else {
        throw new CloudRuntimeException("Failed to create a template");
    }
}
Also used : Account(com.cloud.legacymodel.user.Account) CloudRuntimeException(com.cloud.legacymodel.exceptions.CloudRuntimeException) VMTemplateVO(com.cloud.storage.VMTemplateVO) PermissionDeniedException(com.cloud.legacymodel.exceptions.PermissionDeniedException) TemplateProfile(com.cloud.storage.TemplateProfile) ActionEvent(com.cloud.event.ActionEvent)

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