use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.
the class VolumeApiServiceImpl method extractVolume.
@Override
@ActionEvent(eventType = EventTypes.EVENT_VOLUME_EXTRACT, eventDescription = "extracting volume", async = true)
public String extractVolume(ExtractVolumeCmd cmd) {
Long volumeId = cmd.getId();
Long zoneId = cmd.getZoneId();
String mode = cmd.getMode();
Account account = CallContext.current().getCallingAccount();
if (!_accountMgr.isRootAdmin(account.getId()) && ApiDBUtils.isExtractionDisabled()) {
throw new PermissionDeniedException("Extraction has been disabled by admin");
}
VolumeVO volume = _volsDao.findById(volumeId);
if (volume == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find volume with specified volumeId");
ex.addProxyObject(volumeId.toString(), "volumeId");
throw ex;
}
// perform permission check
_accountMgr.checkAccess(account, null, true, volume);
if (_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.");
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() != Volume.Type.DATADISK) {
// Datadisk dont have any template dependence.
VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
if (template != null) {
// For ISO based volumes template = null and
// we allow extraction of all ISO based
// volumes
boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM;
if (!isExtractable && account != null && !_accountMgr.isRootAdmin(account.getId())) {
// Global admins are always allowed to extract
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
VolumeDataStoreVO volumeStoreRef = _volumeStoreDao.findByVolume(volumeId);
if (volumeStoreRef != null && volumeStoreRef.getExtractUrl() != null) {
return volumeStoreRef.getExtractUrl();
}
VMInstanceVO vm = null;
if (volume.getInstanceId() != null) {
vm = _vmInstanceDao.findById(volume.getInstanceId());
}
if (vm != null) {
// serialize VM operation
AsyncJobExecutionContext jobContext = AsyncJobExecutionContext.getCurrentExecutionContext();
if (jobContext.isJobDispatchedBy(VmWorkConstants.VM_WORK_JOB_DISPATCHER)) {
// avoid re-entrance
VmWorkJobVO placeHolder = null;
placeHolder = createPlaceHolderWork(vm.getId());
try {
return orchestrateExtractVolume(volume.getId(), zoneId);
} finally {
_workJobDao.expunge(placeHolder.getId());
}
} else {
Outcome<String> outcome = extractVolumeThroughJobQueue(vm.getId(), volume.getId(), zoneId);
try {
outcome.get();
} catch (InterruptedException e) {
throw new RuntimeException("Operation is interrupted", e);
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Execution excetion", e);
}
Object jobResult = _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);
}
use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.
the class TemplateManagerImpl method createPrivateTemplateRecord.
@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template", create = true)
public VMTemplateVO createPrivateTemplateRecord(CreateTemplateCmd cmd, Account templateOwner) throws ResourceAllocationException {
Account caller = CallContext.current().getCallingAccount();
boolean isAdmin = (_accountMgr.isAdmin(caller.getId()));
_accountMgr.checkAccess(caller, null, true, templateOwner);
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 (!_accountService.isRootAdmin(caller.getId())) {
throw new PermissionDeniedException("Parameter templatetag can only be specified by a Root Admin, permission denied");
}
}
// do some parameter defaulting
Integer bits = cmd.getBits();
Boolean requiresHvm = cmd.getRequiresHvm();
Boolean passwordEnabled = cmd.isPasswordEnabled();
Boolean isPublic = cmd.isPublic();
Boolean featured = cmd.isFeatured();
int bitsValue = ((bits == null) ? 64 : bits.intValue());
boolean requiresHvmValue = ((requiresHvm == null) ? true : requiresHvm.booleanValue());
boolean passwordEnabledValue = ((passwordEnabled == null) ? false : passwordEnabled.booleanValue());
if (isPublic == null) {
isPublic = Boolean.FALSE;
}
boolean isDynamicScalingEnabled = cmd.isDynamicallyScalable();
// check whether template owner can create public templates
boolean allowPublicUserTemplates = AllowPublicUserTemplates.valueIn(templateOwner.getId());
if (!isAdmin && !allowPublicUserTemplates && isPublic) {
throw new PermissionDeniedException("Failed to create template " + name + ", only private templates can be created.");
}
Long volumeId = cmd.getVolumeId();
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;
VolumeVO volume = null;
SnapshotVO snapshot = null;
VMTemplateVO privateTemplate = null;
if (volumeId != null) {
// create template from volume
volume = _volumeDao.findById(volumeId);
if (volume == null) {
throw new InvalidParameterValueException("Failed to create private template record, unable to find volume " + volumeId);
}
// check permissions
_accountMgr.checkAccess(caller, null, true, volume);
// created
if (!_volumeMgr.volumeInactive(volume)) {
String msg = "Unable to create private template for volume: " + volume.getName() + "; volume is attached to a non-stopped VM, please stop the VM first";
if (s_logger.isInfoEnabled()) {
s_logger.info(msg);
}
throw new CloudRuntimeException(msg);
}
hyperType = _volumeDao.getHypervisorType(volumeId);
if (HypervisorType.LXC.equals(hyperType)) {
throw new InvalidParameterValueException("Template creation is not supported for LXC volume: " + volumeId);
}
} else {
// create template from snapshot
snapshot = _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 = _volumeDao.findByIdIncludingRemoved(snapshot.getVolumeId());
// check permissions
_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();
}
_resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.template);
_resourceLimitMgr.checkResourceLimit(templateOwner, ResourceType.secondary_storage, new Long(volume != null ? volume.getSize() : snapshot.getSize()).longValue());
if (!isAdmin || featured == null) {
featured = Boolean.FALSE;
}
Long guestOSId = cmd.getOsTypeId();
GuestOSVO guestOS = _guestOSDao.findById(guestOSId);
if (guestOS == null) {
throw new InvalidParameterValueException("GuestOS with ID: " + guestOSId + " does not exist.");
}
Long nextTemplateId = _tmpltDao.getNextInSequence(Long.class, "id");
String description = cmd.getDisplayText();
boolean isExtractable = false;
Long sourceTemplateId = null;
if (volume != null) {
VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId());
isExtractable = template != null && template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM;
if (volume.getIsoId() != null && volume.getIsoId() != 0) {
sourceTemplateId = volume.getIsoId();
} else if (volume.getTemplateId() != null) {
sourceTemplateId = volume.getTemplateId();
}
}
String templateTag = cmd.getTemplateTag();
if (templateTag != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Adding template tag: " + templateTag);
}
}
privateTemplate = new VMTemplateVO(nextTemplateId, name, ImageFormat.RAW, isPublic, featured, isExtractable, TemplateType.USER, null, requiresHvmValue, 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
List<ImageStoreVO> stores = _imgStoreDao.findRegionImageStores();
if (!CollectionUtils.isEmpty(stores)) {
privateTemplate.setCrossZones(true);
}
privateTemplate.setSourceTemplateId(sourceTemplateId);
VMTemplateVO template = _tmpltDao.persist(privateTemplate);
// Increment the number of templates
if (template != null) {
Map<String, String> details = new HashMap<String, String>();
if (sourceTemplateId != null) {
VMTemplateVO sourceTemplate = _tmpltDao.findById(sourceTemplateId);
if (sourceTemplate != null && sourceTemplate.getDetails() != null) {
details.putAll(sourceTemplate.getDetails());
}
}
if (volume != null) {
Long vmId = volume.getInstanceId();
if (vmId != null) {
UserVmVO userVm = _userVmDao.findById(vmId);
if (userVm != null) {
_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);
_tmpltDao.saveDetails(privateTemplate);
}
_resourceLimitMgr.incrementResourceCount(templateOwner.getId(), ResourceType.template);
_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");
}
}
use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.
the class TemplateManagerImpl method updateTemplateOrIso.
private VMTemplateVO updateTemplateOrIso(BaseUpdateTemplateOrIsoCmd cmd) {
Long id = cmd.getId();
String name = cmd.getTemplateName();
String displayText = cmd.getDisplayText();
String format = cmd.getFormat();
Long guestOSId = cmd.getOsTypeId();
Boolean passwordEnabled = cmd.getPasswordEnabled();
Boolean isDynamicallyScalable = cmd.isDynamicallyScalable();
Boolean isRoutingTemplate = cmd.isRoutingType();
Boolean bootable = cmd.getBootable();
Boolean requiresHvm = cmd.getRequiresHvm();
Integer sortKey = cmd.getSortKey();
Map details = cmd.getDetails();
Account account = CallContext.current().getCallingAccount();
boolean cleanupDetails = cmd.isCleanupDetails();
// verify that template exists
VMTemplateVO template = _tmpltDao.findById(id);
if (template == null || template.getRemoved() != null) {
InvalidParameterValueException ex = new InvalidParameterValueException("unable to find template/iso with specified id");
ex.addProxyObject(String.valueOf(id), "templateId");
throw ex;
}
verifyTemplateId(id);
// do a permission check
_accountMgr.checkAccess(account, AccessType.OperateEntry, true, template);
if (cmd.isRoutingType() != null) {
if (!_accountService.isRootAdmin(account.getId())) {
throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied");
}
}
// update is needed if any of the fields below got filled by the user
boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null && bootable == null && requiresHvm == null && sortKey == null && isDynamicallyScalable == null && isRoutingTemplate == null && //update details in every case except this one
(!cleanupDetails && details == null));
if (!updateNeeded) {
return template;
}
template = _tmpltDao.createForUpdate(id);
if (name != null) {
template.setName(name);
}
if (displayText != null) {
template.setDisplayText(displayText);
}
if (sortKey != null) {
template.setSortKey(sortKey);
}
ImageFormat imageFormat = null;
if (format != null) {
try {
imageFormat = ImageFormat.valueOf(format.toUpperCase());
} catch (IllegalArgumentException e) {
throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values()));
}
template.setFormat(imageFormat);
}
if (guestOSId != null) {
long oldGuestOSId = template.getGuestOSId();
GuestOSVO guestOS = _guestOSDao.findById(guestOSId);
if (guestOS == null) {
throw new InvalidParameterValueException("Please specify a valid guest OS ID.");
} else {
template.setGuestOSId(guestOSId);
}
if (guestOSId != oldGuestOSId) {
// vm guest os type need to be updated if template guest os id changes.
SearchCriteria<VMInstanceVO> sc = _vmInstanceDao.createSearchCriteria();
sc.addAnd("templateId", SearchCriteria.Op.EQ, id);
sc.addAnd("state", SearchCriteria.Op.NEQ, State.Expunging);
List<VMInstanceVO> vms = _vmInstanceDao.search(sc, null);
if (vms != null && !vms.isEmpty()) {
for (VMInstanceVO vm : vms) {
vm.setGuestOSId(guestOSId);
_vmInstanceDao.update(vm.getId(), vm);
}
}
}
}
if (passwordEnabled != null) {
template.setEnablePassword(passwordEnabled);
}
if (bootable != null) {
template.setBootable(bootable);
}
if (requiresHvm != null) {
template.setRequiresHvm(requiresHvm);
}
if (isDynamicallyScalable != null) {
template.setDynamicallyScalable(isDynamicallyScalable);
}
if (isRoutingTemplate != null) {
if (isRoutingTemplate) {
template.setTemplateType(TemplateType.ROUTING);
} else {
template.setTemplateType(TemplateType.USER);
}
}
if (cleanupDetails) {
template.setDetails(null);
_tmpltDetailsDao.removeDetails(id);
} else if (details != null && !details.isEmpty()) {
template.setDetails(details);
_tmpltDao.saveDetails(template);
}
_tmpltDao.update(id, template);
return _tmpltDao.findById(id);
}
use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.
the class TemplateManagerImpl method registerTemplate.
@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_CREATE, eventDescription = "creating template")
public VirtualMachineTemplate registerTemplate(RegisterTemplateCmd cmd) throws URISyntaxException, ResourceAllocationException {
Account account = CallContext.current().getCallingAccount();
if (cmd.getTemplateTag() != null) {
if (!_accountService.isRootAdmin(account.getId())) {
throw new PermissionDeniedException("Parameter templatetag can only be specified by a Root Admin, permission denied");
}
}
if (cmd.isRoutingType() != null) {
if (!_accountService.isRootAdmin(account.getId())) {
throw new PermissionDeniedException("Parameter isrouting can only be specified by a Root Admin, permission denied");
}
}
TemplateAdapter adapter = getAdapter(HypervisorType.getType(cmd.getHypervisor()));
TemplateProfile profile = adapter.prepare(cmd);
VMTemplateVO template = adapter.create(profile);
if (template != null) {
return template;
} else {
throw new CloudRuntimeException("Failed to create a template");
}
}
use of com.cloud.exception.PermissionDeniedException in project cloudstack by apache.
the class TemplateManagerImpl method listTemplatePermissions.
@Override
public List<String> listTemplatePermissions(BaseListTemplateOrIsoPermissionsCmd cmd) {
Account caller = CallContext.current().getCallingAccount();
Long id = cmd.getId();
if (id.equals(Long.valueOf(1))) {
throw new PermissionDeniedException("unable to list permissions for " + cmd.getMediaType() + " with id " + id);
}
VirtualMachineTemplate template = _tmpltDao.findById(id);
if (template == null) {
throw new InvalidParameterValueException("unable to find " + cmd.getMediaType() + " with id " + id);
}
if (cmd instanceof ListTemplatePermissionsCmd) {
if (template.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Please provide a valid template");
}
} else if (cmd instanceof ListIsoPermissionsCmd) {
if (!template.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Please provide a valid iso");
}
}
if (!template.isPublicTemplate()) {
_accountMgr.checkAccess(caller, null, true, template);
}
List<String> accountNames = new ArrayList<String>();
List<LaunchPermissionVO> permissions = _launchPermissionDao.findByTemplate(id);
if ((permissions != null) && !permissions.isEmpty()) {
for (LaunchPermissionVO permission : permissions) {
Account acct = _accountDao.findById(permission.getAccountId());
accountNames.add(acct.getAccountName());
}
}
// also add the owner if not public
if (!template.isPublicTemplate()) {
Account templateOwner = _accountDao.findById(template.getAccountId());
accountNames.add(templateOwner.getAccountName());
}
return accountNames;
}
Aggregations