use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.
the class TemplateManagerImpl method prepareTemplate.
@Override
public VirtualMachineTemplate prepareTemplate(long templateId, long zoneId, Long storageId) {
VMTemplateVO vmTemplate = _tmpltDao.findById(templateId);
if (vmTemplate == null) {
throw new InvalidParameterValueException("Unable to find template id=" + templateId);
}
_accountMgr.checkAccess(CallContext.current().getCallingAccount(), AccessType.OperateEntry, true, vmTemplate);
if (storageId != null) {
StoragePoolVO pool = _poolDao.findById(storageId);
if (pool != null) {
if (pool.getStatus() == StoragePoolStatus.Up && pool.getDataCenterId() == zoneId) {
prepareTemplateInOneStoragePool(vmTemplate, pool);
} else {
s_logger.warn("Skip loading template " + vmTemplate.getId() + " into primary storage " + pool.getId() + " as either the pool zone " + pool.getDataCenterId() + " is different from the requested zone " + zoneId + " or the pool is currently not available.");
}
}
} else {
prepareTemplateInAllStoragePools(vmTemplate, zoneId);
}
return vmTemplate;
}
use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.
the class TemplateManagerImpl method updateTemplateOrIsoPermissions.
@DB
@Override
public boolean updateTemplateOrIsoPermissions(BaseUpdateTemplateOrIsoPermissionsCmd cmd) {
// Input validation
final Long id = cmd.getId();
final Account caller = CallContext.current().getCallingAccount();
List<String> accountNames = cmd.getAccountNames();
List<Long> projectIds = cmd.getProjectIds();
Boolean isFeatured = cmd.isFeatured();
Boolean isPublic = cmd.isPublic();
Boolean isExtractable = cmd.isExtractable();
String operation = cmd.getOperation();
String mediaType = "";
VMTemplateVO template = _tmpltDao.findById(id);
if (template == null) {
throw new InvalidParameterValueException("unable to find " + mediaType + " with id " + id);
}
if (cmd instanceof UpdateTemplatePermissionsCmd) {
mediaType = "template";
if (template.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Please provide a valid template");
}
}
if (cmd instanceof UpdateIsoPermissionsCmd) {
mediaType = "iso";
if (!template.getFormat().equals(ImageFormat.ISO)) {
throw new InvalidParameterValueException("Please provide a valid iso");
}
}
// convert projectIds to accountNames
if (projectIds != null) {
// CS-17842, initialize accountNames list
if (accountNames == null) {
accountNames = new ArrayList<String>();
}
for (Long projectId : projectIds) {
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 InvalidParameterValueException("Account " + caller + " can't access project id=" + projectId);
}
accountNames.add(_accountMgr.getAccount(project.getProjectAccountId()).getAccountName());
}
}
//_accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, template);
//TODO: should we replace all ModifyEntry as OperateEntry?
_accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template);
// If the template is removed throw an error.
if (template.getRemoved() != null) {
s_logger.error("unable to update permissions for " + mediaType + " with id " + id + " as it is removed ");
throw new InvalidParameterValueException("unable to update permissions for " + mediaType + " with id " + id + " as it is removed ");
}
if (id.equals(Long.valueOf(1))) {
throw new InvalidParameterValueException("unable to update permissions for " + mediaType + " with id " + id);
}
boolean isAdmin = _accountMgr.isAdmin(caller.getId());
// check configuration parameter(allow.public.user.templates) value for
// the template owner
boolean allowPublicUserTemplates = AllowPublicUserTemplates.valueIn(template.getAccountId());
if (!isAdmin && !allowPublicUserTemplates && isPublic != null && isPublic) {
throw new InvalidParameterValueException("Only private " + mediaType + "s can be created.");
}
if (accountNames != null) {
if ((operation == null) || (!operation.equalsIgnoreCase("add") && !operation.equalsIgnoreCase("remove") && !operation.equalsIgnoreCase("reset"))) {
throw new InvalidParameterValueException("Invalid operation on accounts, the operation must be either 'add' or 'remove' in order to modify launch permissions." + " Given operation is: '" + operation + "'");
}
}
Long ownerId = template.getAccountId();
if (ownerId == null) {
// publishing to individual users is irrelevant
throw new InvalidParameterValueException("Update template permissions is an invalid operation on template " + template.getName());
}
//Only admin or owner of the template should be able to change its permissions
if (caller.getId() != ownerId && !isAdmin) {
throw new InvalidParameterValueException("Unable to grant permission to account " + caller.getAccountName() + " as it is neither admin nor owner or the template");
}
VMTemplateVO updatedTemplate = _tmpltDao.createForUpdate();
if (isPublic != null) {
updatedTemplate.setPublicTemplate(isPublic.booleanValue());
}
if (isFeatured != null) {
updatedTemplate.setFeatured(isFeatured.booleanValue());
}
if (isExtractable != null) {
// Only Root admins allowed to change it for templates
if (!template.getFormat().equals(ImageFormat.ISO) && !_accountMgr.isRootAdmin(caller.getId())) {
throw new InvalidParameterValueException("Only ROOT admins are allowed to modify isExtractable attribute.");
} else {
// For Isos normal user can change it, as their are no derivatives.
updatedTemplate.setExtractable(isExtractable.booleanValue());
}
}
_tmpltDao.update(template.getId(), updatedTemplate);
//when operation is add/remove, accountNames can not be null
if (("add".equalsIgnoreCase(operation) || "remove".equalsIgnoreCase(operation)) && accountNames == null) {
throw new InvalidParameterValueException("Operation " + operation + " requires accounts or projectIds to be passed in");
}
//Derive the domain id from the template owner as updateTemplatePermissions is not cross domain operation
Account owner = _accountMgr.getAccount(ownerId);
final Domain domain = _domainDao.findById(owner.getDomainId());
if ("add".equalsIgnoreCase(operation)) {
final List<String> accountNamesFinal = accountNames;
final List<Long> accountIds = new ArrayList<Long>();
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
for (String accountName : accountNamesFinal) {
Account permittedAccount = _accountDao.findActiveAccount(accountName, domain.getId());
if (permittedAccount != null) {
if (permittedAccount.getId() == caller.getId()) {
// don't grant permission to the template
continue;
// owner, they implicitly have permission
}
accountIds.add(permittedAccount.getId());
LaunchPermissionVO existingPermission = _launchPermissionDao.findByTemplateAndAccount(id, permittedAccount.getId());
if (existingPermission == null) {
LaunchPermissionVO launchPermission = new LaunchPermissionVO(id, permittedAccount.getId());
_launchPermissionDao.persist(launchPermission);
}
} else {
throw new InvalidParameterValueException("Unable to grant a launch permission to account " + accountName + " in domain id=" + domain.getUuid() + ", account not found. " + "No permissions updated, please verify the account names and retry.");
}
}
}
});
// add ACL permission in IAM
Map<String, Object> permit = new HashMap<String, Object>();
permit.put(ApiConstants.ENTITY_TYPE, VirtualMachineTemplate.class);
permit.put(ApiConstants.ENTITY_ID, id);
permit.put(ApiConstants.ACCESS_TYPE, AccessType.UseEntry);
permit.put(ApiConstants.IAM_ACTION, "listTemplates");
permit.put(ApiConstants.ACCOUNTS, accountIds);
_messageBus.publish(_name, EntityManager.MESSAGE_GRANT_ENTITY_EVENT, PublishScope.LOCAL, permit);
} else if ("remove".equalsIgnoreCase(operation)) {
List<Long> accountIds = new ArrayList<Long>();
for (String accountName : accountNames) {
Account permittedAccount = _accountDao.findActiveAccount(accountName, domain.getId());
if (permittedAccount != null) {
accountIds.add(permittedAccount.getId());
}
}
_launchPermissionDao.removePermissions(id, accountIds);
// remove ACL permission in IAM
Map<String, Object> permit = new HashMap<String, Object>();
permit.put(ApiConstants.ENTITY_TYPE, VirtualMachineTemplate.class);
permit.put(ApiConstants.ENTITY_ID, id);
permit.put(ApiConstants.ACCESS_TYPE, AccessType.UseEntry);
permit.put(ApiConstants.IAM_ACTION, "listTemplates");
permit.put(ApiConstants.ACCOUNTS, accountIds);
_messageBus.publish(_name, EntityManager.MESSAGE_REVOKE_ENTITY_EVENT, PublishScope.LOCAL, permit);
} else if ("reset".equalsIgnoreCase(operation)) {
// do we care whether the owning account is an admin? if the
// owner is an admin, will we still set public to false?
updatedTemplate = _tmpltDao.createForUpdate();
updatedTemplate.setPublicTemplate(false);
updatedTemplate.setFeatured(false);
_tmpltDao.update(template.getId(), updatedTemplate);
_launchPermissionDao.removeAllPermissions(id);
_messageBus.publish(_name, TemplateManager.MESSAGE_RESET_TEMPLATE_PERMISSION_EVENT, PublishScope.LOCAL, template.getId());
}
return true;
}
use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.
the class TemplateManagerImpl method templateIsDeleteable.
@Override
public boolean templateIsDeleteable(VMTemplateHostVO templateHostRef) {
VMTemplateVO template = _tmpltDao.findByIdIncludingRemoved(templateHostRef.getTemplateId());
long templateId = template.getId();
HostVO secondaryStorageHost = _hostDao.findById(templateHostRef.getHostId());
long zoneId = secondaryStorageHost.getDataCenterId();
DataCenterVO zone = _dcDao.findById(zoneId);
// Check if there are VMs running in the template host ref's zone that
// use the template
List<VMInstanceVO> nonExpungedVms = _vmInstanceDao.listNonExpungedByZoneAndTemplate(zoneId, templateId);
if (!nonExpungedVms.isEmpty()) {
s_logger.debug("Template " + template.getName() + " in zone " + zone.getName() + " is not deleteable because there are non-expunged VMs deployed from this template.");
return false;
}
List<UserVmVO> userVmUsingIso = _userVmDao.listByIsoId(templateId);
// check if there is any VM using this ISO.
if (!userVmUsingIso.isEmpty()) {
s_logger.debug("ISO " + template.getName() + " in zone " + zone.getName() + " is not deleteable because it is attached to " + userVmUsingIso.size() + " VMs");
return false;
}
// Check if there are any snapshots for the template in the template
// host ref's zone
List<VolumeVO> volumes = _volumeDao.findByTemplateAndZone(templateId, zoneId);
for (VolumeVO volume : volumes) {
List<SnapshotVO> snapshots = _snapshotDao.listByVolumeIdVersion(volume.getId(), "2.1");
if (!snapshots.isEmpty()) {
s_logger.debug("Template " + template.getName() + " in zone " + zone.getName() + " is not deleteable because there are 2.1 snapshots using this template.");
return false;
}
}
return true;
}
use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.
the class TemplateManagerImpl method attachIso.
@Override
@ActionEvent(eventType = EventTypes.EVENT_ISO_ATTACH, eventDescription = "attaching ISO", async = true)
public boolean attachIso(long isoId, long vmId) {
Account caller = CallContext.current().getCallingAccount();
Long userId = CallContext.current().getCallingUserId();
// Verify input parameters
UserVmVO vm = _userVmDao.findById(vmId);
if (vm == null) {
throw new InvalidParameterValueException("Unable to find a virtual machine with id " + vmId);
}
VMTemplateVO iso = _tmpltDao.findById(isoId);
if (iso == null || iso.getRemoved() != null) {
throw new InvalidParameterValueException("Unable to find an ISO with id " + isoId);
}
// check permissions
// check if caller has access to VM and ISO
// and also check if the VM's owner has access to the ISO.
_accountMgr.checkAccess(caller, null, false, iso, vm);
Account vmOwner = _accountDao.findById(vm.getAccountId());
_accountMgr.checkAccess(vmOwner, null, false, iso, vm);
State vmState = vm.getState();
if (vmState != State.Running && vmState != State.Stopped) {
throw new InvalidParameterValueException("Please specify a VM that is either Stopped or Running.");
}
if ("xen-pv-drv-iso".equals(iso.getDisplayText()) && vm.getHypervisorType() != Hypervisor.HypervisorType.XenServer) {
throw new InvalidParameterValueException("Cannot attach Xenserver PV drivers to incompatible hypervisor " + vm.getHypervisorType());
}
if ("vmware-tools.iso".equals(iso.getName()) && vm.getHypervisorType() != Hypervisor.HypervisorType.VMware) {
throw new InvalidParameterValueException("Cannot attach VMware tools drivers to incompatible hypervisor " + vm.getHypervisorType());
}
boolean result = attachISOToVM(vmId, userId, isoId, true);
if (result) {
return result;
} else {
throw new CloudRuntimeException("Failed to attach iso");
}
}
use of com.cloud.storage.VMTemplateVO in project cloudstack by apache.
the class TemplateManagerImpl method deleteTemplate.
@Override
@ActionEvent(eventType = EventTypes.EVENT_TEMPLATE_DELETE, eventDescription = "deleting template", async = true)
public boolean deleteTemplate(DeleteTemplateCmd cmd) {
Long templateId = cmd.getId();
Account caller = CallContext.current().getCallingAccount();
VMTemplateVO template = _tmpltDao.findById(templateId);
if (template == null) {
throw new InvalidParameterValueException("unable to find template with id " + templateId);
}
_accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template);
if (template.getFormat() == ImageFormat.ISO) {
throw new InvalidParameterValueException("Please specify a valid template.");
}
TemplateAdapter adapter = getAdapter(template.getHypervisorType());
TemplateProfile profile = adapter.prepareDelete(cmd);
return adapter.delete(profile);
}
Aggregations