Search in sources :

Example 81 with Project

use of com.cloud.projects.Project 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);
    }
    Long ownerId = template.getAccountId();
    Account owner = _accountMgr.getAccount(ownerId);
    if (ownerId == null) {
        // publishing to individual users is irrelevant
        throw new InvalidParameterValueException("Update template permissions is an invalid operation on template " + template.getName());
    }
    if (owner.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        // Currently project owned templates cannot be shared outside project but is available to all users within project by default.
        throw new InvalidParameterValueException("Update template permissions is an invalid operation on template " + template.getName() + ". Project owned templates cannot be shared outside template.");
    }
    // check configuration parameter(allow.public.user.templates) value for
    // the template owner
    boolean isAdmin = _accountMgr.isAdmin(caller.getId());
    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 + "'");
        }
    }
    // 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 and owners are allowed to change it for templates
        if (!template.getFormat().equals(ImageFormat.ISO) && caller.getId() != ownerId && !isAdmin) {
            throw new InvalidParameterValueException("Only ROOT admins and template owners 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
    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.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.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;
}
Also used : Account(com.cloud.user.Account) HashMap(java.util.HashMap) VMTemplateVO(com.cloud.storage.VMTemplateVO) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) UpdateTemplatePermissionsCmd(org.apache.cloudstack.api.command.user.template.UpdateTemplatePermissionsCmd) LaunchPermissionVO(com.cloud.storage.LaunchPermissionVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) UpdateIsoPermissionsCmd(org.apache.cloudstack.api.command.user.iso.UpdateIsoPermissionsCmd) ArrayList(java.util.ArrayList) List(java.util.List) Project(com.cloud.projects.Project) Domain(com.cloud.domain.Domain) Map(java.util.Map) HashMap(java.util.HashMap) DB(com.cloud.utils.db.DB)

Example 82 with Project

use of com.cloud.projects.Project in project cloudstack by apache.

the class ApiResponseHelper method populateOwner.

// TODO: we may need to refactor once ControlledEntityResponse and
// ControlledEntity id to uuid conversion are all done.
// currently code is scattered in
private void populateOwner(ControlledEntityResponse response, ControlledEntity object) {
    Account account = ApiDBUtils.findAccountById(object.getAccountId());
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        // find the project
        Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId());
        response.setProjectId(project.getUuid());
        response.setProjectName(project.getName());
    } else {
        response.setAccountName(account.getAccountName());
    }
    Domain domain = ApiDBUtils.findDomainById(object.getDomainId());
    response.setDomainId(domain.getUuid());
    response.setDomainName(domain.getName());
}
Also used : ProjectAccount(com.cloud.projects.ProjectAccount) UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) Project(com.cloud.projects.Project) Domain(com.cloud.domain.Domain)

Example 83 with Project

use of com.cloud.projects.Project in project cloudstack by apache.

the class ApiResponseHelper method createVMSnapshotResponse.

@Override
public VMSnapshotResponse createVMSnapshotResponse(VMSnapshot vmSnapshot) {
    VMSnapshotResponse vmSnapshotResponse = new VMSnapshotResponse();
    vmSnapshotResponse.setId(vmSnapshot.getUuid());
    vmSnapshotResponse.setName(vmSnapshot.getName());
    vmSnapshotResponse.setState(vmSnapshot.getState());
    vmSnapshotResponse.setCreated(vmSnapshot.getCreated());
    vmSnapshotResponse.setDescription(vmSnapshot.getDescription());
    vmSnapshotResponse.setDisplayName(vmSnapshot.getDisplayName());
    UserVm vm = ApiDBUtils.findUserVmById(vmSnapshot.getVmId());
    if (vm != null) {
        vmSnapshotResponse.setVirtualMachineId(vm.getUuid());
        vmSnapshotResponse.setVirtualMachineName(StringUtils.isEmpty(vm.getDisplayName()) ? vm.getHostName() : vm.getDisplayName());
        vmSnapshotResponse.setHypervisor(vm.getHypervisorType());
        DataCenterVO datacenter = ApiDBUtils.findZoneById(vm.getDataCenterId());
        if (datacenter != null) {
            vmSnapshotResponse.setZoneId(datacenter.getUuid());
            vmSnapshotResponse.setZoneName(datacenter.getName());
        }
    }
    if (vmSnapshot.getParent() != null) {
        VMSnapshot vmSnapshotParent = ApiDBUtils.getVMSnapshotById(vmSnapshot.getParent());
        if (vmSnapshotParent != null) {
            vmSnapshotResponse.setParent(vmSnapshotParent.getUuid());
            vmSnapshotResponse.setParentName(vmSnapshotParent.getDisplayName());
        }
    }
    populateOwner(vmSnapshotResponse, vmSnapshot);
    Project project = ApiDBUtils.findProjectByProjectAccountId(vmSnapshot.getAccountId());
    if (project != null) {
        vmSnapshotResponse.setProjectId(project.getUuid());
        vmSnapshotResponse.setProjectName(project.getName());
    }
    Account account = ApiDBUtils.findAccountById(vmSnapshot.getAccountId());
    if (account != null) {
        vmSnapshotResponse.setAccountName(account.getAccountName());
    }
    DomainVO domain = ApiDBUtils.findDomainById(vmSnapshot.getDomainId());
    if (domain != null) {
        vmSnapshotResponse.setDomainId(domain.getUuid());
        vmSnapshotResponse.setDomainName(domain.getName());
    }
    List<? extends ResourceTag> tags = _resourceTagDao.listBy(vmSnapshot.getId(), ResourceObjectType.VMSnapshot);
    List<ResourceTagResponse> tagResponses = new ArrayList<ResourceTagResponse>();
    for (ResourceTag tag : tags) {
        ResourceTagResponse tagResponse = createResourceTagResponse(tag, false);
        CollectionUtils.addIgnoreNull(tagResponses, tagResponse);
    }
    vmSnapshotResponse.setTags(new HashSet<>(tagResponses));
    vmSnapshotResponse.setHasAnnotation(annotationDao.hasAnnotations(vmSnapshot.getUuid(), AnnotationService.EntityType.VM_SNAPSHOT.name(), _accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())));
    vmSnapshotResponse.setCurrent(vmSnapshot.getCurrent());
    vmSnapshotResponse.setType(vmSnapshot.getType().toString());
    vmSnapshotResponse.setObjectName("vmsnapshot");
    return vmSnapshotResponse;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) ProjectAccount(com.cloud.projects.ProjectAccount) UserAccount(com.cloud.user.UserAccount) Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) VMSnapshot(com.cloud.vm.snapshot.VMSnapshot) Project(com.cloud.projects.Project) DomainVO(com.cloud.domain.DomainVO) UserVm(com.cloud.uservm.UserVm) ResourceTag(com.cloud.server.ResourceTag) VMSnapshotResponse(org.apache.cloudstack.api.response.VMSnapshotResponse) ResourceTagResponse(org.apache.cloudstack.api.response.ResourceTagResponse)

Example 84 with Project

use of com.cloud.projects.Project in project cloudstack by apache.

the class ApiDispatcher method dispatch.

public void dispatch(final BaseCmd cmd, final Map<String, String> params, final boolean execute) throws Exception {
    // Let the chain of responsibility dispatch gradually
    standardDispatchChain.dispatch(new DispatchTask(cmd, params));
    final CallContext ctx = CallContext.current();
    ctx.setEventDisplayEnabled(cmd.isDisplay());
    if (params.get(ApiConstants.PROJECT_ID) != null) {
        Project project = _entityMgr.findByUuidIncludingRemoved(Project.class, params.get(ApiConstants.PROJECT_ID));
        ctx.setProject(project);
    }
    // TODO This if shouldn't be here. Use polymorphism and move it to validateSpecificParameters
    if (cmd instanceof BaseAsyncCmd) {
        final BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmd;
        final String startEventId = params.get(ApiConstants.CTX_START_EVENT_ID);
        ctx.setStartEventId(Long.parseLong(startEventId));
        // Synchronise job on the object if needed
        if (asyncCmd.getJob() != null && asyncCmd.getSyncObjId() != null && asyncCmd.getSyncObjType() != null) {
            Long queueSizeLimit = null;
            if (asyncCmd.getSyncObjType() != null && asyncCmd.getSyncObjType().equalsIgnoreCase(BaseAsyncCmd.snapshotHostSyncObject)) {
                queueSizeLimit = _createSnapshotQueueSizeLimit;
            } else if (asyncCmd.getSyncObjType() != null && asyncCmd.getSyncObjType().equalsIgnoreCase(BaseAsyncCmd.migrationSyncObject)) {
                queueSizeLimit = migrateQueueSizeLimit;
            } else {
                queueSizeLimit = 1L;
            }
            if (queueSizeLimit != null) {
                if (!execute) {
                    // if we are not within async-execution context, enqueue the command
                    _asyncMgr.syncAsyncJobExecution((AsyncJob) asyncCmd.getJob(), asyncCmd.getSyncObjType(), asyncCmd.getSyncObjId().longValue(), queueSizeLimit);
                    return;
                }
            } else {
                s_logger.trace("The queue size is unlimited, skipping the synchronizing");
            }
        }
    }
    // TODO This if shouldn't be here. Use polymorphism and move it to validateSpecificParameters
    if (cmd instanceof BaseAsyncCustomIdCmd) {
        ((BaseAsyncCustomIdCmd) cmd).checkUuid();
    } else if (cmd instanceof BaseCustomIdCmd) {
        ((BaseCustomIdCmd) cmd).checkUuid();
    }
    cmd.execute();
}
Also used : Project(com.cloud.projects.Project) BaseCustomIdCmd(org.apache.cloudstack.api.BaseCustomIdCmd) CallContext(org.apache.cloudstack.context.CallContext) DispatchTask(com.cloud.api.dispatch.DispatchTask) BaseAsyncCmd(org.apache.cloudstack.api.BaseAsyncCmd) BaseAsyncCustomIdCmd(org.apache.cloudstack.api.BaseAsyncCustomIdCmd)

Example 85 with Project

use of com.cloud.projects.Project in project cloudstack by apache.

the class DomainChecker method checkOperationPermitted.

private boolean checkOperationPermitted(Account caller, ControlledEntity entity) {
    User user = CallContext.current().getCallingUser();
    Project project = projectDao.findByProjectAccountId(entity.getAccountId());
    if (project == null) {
        throw new CloudRuntimeException("Unable to find project to which the entity belongs to");
    }
    ProjectAccount projectUser = _projectAccountDao.findByProjectIdUserId(project.getId(), user.getAccountId(), user.getId());
    String apiCommandName = CallContext.current().getApiName();
    if (accountService.isRootAdmin(caller.getId()) || accountService.isDomainAdmin(caller.getAccountId())) {
        return true;
    }
    if (projectUser != null) {
        if (projectUser.getAccountRole() == ProjectAccount.Role.Admin) {
            return true;
        } else {
            return isPermitted(project, projectUser, apiCommandName);
        }
    }
    ProjectAccount projectAccount = _projectAccountDao.findByProjectIdAccountId(project.getId(), caller.getAccountId());
    if (projectAccount != null) {
        if (projectAccount.getAccountRole() == ProjectAccount.Role.Admin) {
            return true;
        } else {
            return isPermitted(project, projectAccount, apiCommandName);
        }
    }
    throw new UnavailableCommandException("The given command '" + apiCommandName + "' either does not exist or is not available for the user");
}
Also used : Project(com.cloud.projects.Project) ProjectAccount(com.cloud.projects.ProjectAccount) User(com.cloud.user.User) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) UnavailableCommandException(com.cloud.exception.UnavailableCommandException)

Aggregations

Project (com.cloud.projects.Project)89 Account (com.cloud.user.Account)55 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)28 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)27 Domain (com.cloud.domain.Domain)20 ArrayList (java.util.ArrayList)20 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)18 DomainVO (com.cloud.domain.DomainVO)12 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)11 Pair (com.cloud.utils.Pair)11 List (java.util.List)11 ServerApiException (com.cloud.api.ServerApiException)10 ProjectAccount (com.cloud.projects.ProjectAccount)10 Volume (com.cloud.storage.Volume)10 UserAccount (com.cloud.user.UserAccount)10 DB (com.cloud.utils.db.DB)10 ProjectResponse (com.cloud.api.response.ProjectResponse)9 Filter (com.cloud.utils.db.Filter)9 DataCenterVO (com.cloud.dc.DataCenterVO)8 VlanVO (com.cloud.dc.VlanVO)6