Search in sources :

Example 16 with Domain

use of com.cloud.legacymodel.domain.Domain in project cosmic by MissionCriticalCloud.

the class DomainManagerImpl method getDomainByName.

@Override
public Domain getDomainByName(final String name, final long parentId) {
    final SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
    sc.addAnd("name", SearchCriteria.Op.EQ, name);
    sc.addAnd("parent", SearchCriteria.Op.EQ, parentId);
    final Domain domain = _domainDao.findOneBy(sc);
    return domain;
}
Also used : DomainVO(com.cloud.domain.DomainVO) Domain(com.cloud.legacymodel.domain.Domain)

Example 17 with Domain

use of com.cloud.legacymodel.domain.Domain in project cosmic by MissionCriticalCloud.

the class TemplateManagerImpl method updateTemplateOrIsoPermissions.

@DB
@Override
public boolean updateTemplateOrIsoPermissions(final BaseUpdateTemplateOrIsoPermissionsCmd cmd) {
    // Input validation
    final Long id = cmd.getId();
    final Account caller = CallContext.current().getCallingAccount();
    List<String> accountNames = cmd.getAccountNames();
    final List<Long> projectIds = cmd.getProjectIds();
    final Boolean isFeatured = cmd.isFeatured();
    final Boolean isPublic = cmd.isPublic();
    final Boolean isExtractable = cmd.isExtractable();
    final String operation = cmd.getOperation();
    String mediaType = "";
    final VMTemplateVO template = this._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<>();
        }
        for (final Long projectId : projectIds) {
            final Project project = this._projectMgr.getProject(projectId);
            if (project == null) {
                throw new InvalidParameterValueException("Unable to find project by id " + projectId);
            }
            if (!this._projectMgr.canAccessProjectAccount(caller, project.getProjectAccountId())) {
                throw new InvalidParameterValueException("Account " + caller + " can't access project id=" + projectId);
            }
            accountNames.add(this._accountMgr.getAccount(project.getProjectAccountId()).getAccountName());
        }
    }
    // _accountMgr.checkAccess(caller, AccessType.ModifyEntry, true, template);
    // TODO: should we replace all ModifyEntry as OperateEntry?
    this._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);
    }
    final boolean isAdmin = this._accountMgr.isAdmin(caller.getId());
    // check configuration parameter(allow.public.user.templates) value for
    // the template owner
    final 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 + "'");
        }
    }
    final 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 = this._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) && !this._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());
        }
    }
    this._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 Account owner = this._accountMgr.getAccount(ownerId);
    final Domain domain = this._domainDao.findById(owner.getDomainId());
    if ("add".equalsIgnoreCase(operation)) {
        final List<String> accountNamesFinal = accountNames;
        final List<Long> accountIds = new ArrayList<>();
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(final TransactionStatus status) {
                for (final String accountName : accountNamesFinal) {
                    final Account permittedAccount = TemplateManagerImpl.this._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());
                        final LaunchPermissionVO existingPermission = TemplateManagerImpl.this._launchPermissionDao.findByTemplateAndAccount(id, permittedAccount.getId());
                        if (existingPermission == null) {
                            final LaunchPermissionVO launchPermission = new LaunchPermissionVO(id, permittedAccount.getId());
                            TemplateManagerImpl.this._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.");
                    }
                }
            }
        });
    } else if ("remove".equalsIgnoreCase(operation)) {
        final List<Long> accountIds = new ArrayList<>();
        for (final String accountName : accountNames) {
            final Account permittedAccount = this._accountDao.findActiveAccount(accountName, domain.getId());
            if (permittedAccount != null) {
                accountIds.add(permittedAccount.getId());
            }
        }
        this._launchPermissionDao.removePermissions(id, accountIds);
    } 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 = this._tmpltDao.createForUpdate();
        updatedTemplate.setPublicTemplate(false);
        updatedTemplate.setFeatured(false);
        this._tmpltDao.update(template.getId(), updatedTemplate);
        this._launchPermissionDao.removeAllPermissions(id);
        this._messageBus.publish(this._name, TemplateManager.MESSAGE_RESET_TEMPLATE_PERMISSION_EVENT, PublishScope.LOCAL, template.getId());
    }
    return true;
}
Also used : Account(com.cloud.legacymodel.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) UpdateTemplatePermissionsCmd(com.cloud.api.command.user.template.UpdateTemplatePermissionsCmd) LaunchPermissionVO(com.cloud.storage.LaunchPermissionVO) Project(com.cloud.projects.Project) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) UpdateIsoPermissionsCmd(com.cloud.api.command.user.iso.UpdateIsoPermissionsCmd) ArrayList(java.util.ArrayList) List(java.util.List) Domain(com.cloud.legacymodel.domain.Domain) DB(com.cloud.utils.db.DB)

Example 18 with Domain

use of com.cloud.legacymodel.domain.Domain in project cosmic by MissionCriticalCloud.

the class DomainManagerImpl method updateDomain.

@Override
@ActionEvent(eventType = EventTypes.EVENT_DOMAIN_UPDATE, eventDescription = "updating Domain")
@DB
public DomainVO updateDomain(final UpdateDomainCmd cmd) {
    final Long domainId = cmd.getId();
    final String domainName = cmd.getDomainName();
    final String networkDomain = cmd.getNetworkDomain();
    final String email = cmd.getEmail();
    final String slackChannelName = cmd.getSlackChannelName();
    // check if domain exists in the system
    final DomainVO domain = _domainDao.findById(domainId);
    if (domain == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id");
        ex.addProxyObject(domainId.toString(), "domainId");
        throw ex;
    } else if (domain.getParent() == null && domainName != null) {
        // check if domain is ROOT domain - and deny to edit it with the new name
        throw new InvalidParameterValueException("ROOT domain can not be edited with a new name");
    }
    // check permissions
    final Account caller = CallContext.current().getCallingAccount();
    _accountMgr.checkAccess(caller, domain);
    // domain name is unique in the cloud
    if (domainName != null) {
        final SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
        sc.addAnd("name", SearchCriteria.Op.EQ, domainName);
        final List<DomainVO> domains = _domainDao.search(sc, null);
        final boolean sameDomain = (domains.size() == 1 && domains.get(0).getId() == domainId);
        if (!domains.isEmpty() && !sameDomain) {
            final InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system");
            ex.addProxyObject(domain.getUuid(), "domainId");
            throw ex;
        }
    }
    // validate network domain
    if (networkDomain != null && !networkDomain.isEmpty()) {
        if (!NetUtils.verifyDomainName(networkDomain)) {
            throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters " + "'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
        }
    }
    final EmailValidator validator = EmailValidator.getInstance();
    if (!StringUtils.isEmpty(email) && !validator.isValid(email)) {
        throw new InvalidParameterValueException("Email address is not formatted correctly");
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            if (domainName != null) {
                final String updatedDomainPath = getUpdatedDomainPath(domain.getPath(), domainName);
                updateDomainChildren(domain, updatedDomainPath);
                domain.setName(domainName);
                domain.setPath(updatedDomainPath);
            }
            if (networkDomain != null) {
                if (networkDomain.isEmpty()) {
                    domain.setNetworkDomain(null);
                } else {
                    domain.setNetworkDomain(networkDomain);
                }
            }
            if (email != null) {
                if (email.isEmpty()) {
                    domain.setEmail(null);
                } else {
                    domain.setEmail(email);
                }
            }
            if (slackChannelName != null) {
                if (slackChannelName.isEmpty()) {
                    domain.setSlackChannelName(null);
                } else {
                    domain.setSlackChannelName(slackChannelName);
                }
            }
            _domainDao.update(domainId, domain);
            CallContext.current().putContextParameter(Domain.class, domain.getUuid());
        }
    });
    return _domainDao.findById(domainId);
}
Also used : Account(com.cloud.legacymodel.user.Account) EmailValidator(org.apache.commons.validator.routines.EmailValidator) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) DomainVO(com.cloud.domain.DomainVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Domain(com.cloud.legacymodel.domain.Domain) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 19 with Domain

use of com.cloud.legacymodel.domain.Domain in project cosmic by MissionCriticalCloud.

the class DomainManagerImpl method searchForDomains.

@Override
public Pair<List<? extends Domain>, Integer> searchForDomains(final ListDomainsCmd cmd) {
    final Account caller = CallContext.current().getCallingAccount();
    Long domainId = cmd.getId();
    final boolean listAll = cmd.listAll();
    boolean isRecursive = false;
    if (domainId != null) {
        final Domain domain = getDomain(domainId);
        if (domain == null) {
            throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist");
        }
        _accountMgr.checkAccess(caller, domain);
    } else {
        if (!_accountMgr.isRootAdmin(caller.getId())) {
            domainId = caller.getDomainId();
        }
        if (listAll) {
            isRecursive = true;
        }
    }
    final Filter searchFilter = new Filter(DomainVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    final String domainName = cmd.getDomainName();
    final Integer level = cmd.getLevel();
    final Object keyword = cmd.getKeyword();
    final SearchBuilder<DomainVO> sb = _domainDao.createSearchBuilder();
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ);
    sb.and("level", sb.entity().getLevel(), SearchCriteria.Op.EQ);
    sb.and("path", sb.entity().getPath(), SearchCriteria.Op.LIKE);
    sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ);
    final SearchCriteria<DomainVO> sc = sb.create();
    if (keyword != null) {
        final SearchCriteria<DomainVO> ssc = _domainDao.createSearchCriteria();
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    if (domainName != null) {
        sc.setParameters("name", domainName);
    }
    if (level != null) {
        sc.setParameters("level", level);
    }
    if (domainId != null) {
        if (isRecursive) {
            sc.setParameters("path", getDomain(domainId).getPath() + "%");
        } else {
            sc.setParameters("id", domainId);
        }
    }
    // return only Active domains to the API
    sc.setParameters("state", Domain.State.Active);
    final Pair<List<DomainVO>, Integer> result = _domainDao.searchAndCount(sc, searchFilter);
    return new Pair<>(result.first(), result.second());
}
Also used : Account(com.cloud.legacymodel.user.Account) DomainVO(com.cloud.domain.DomainVO) InvalidParameterValueException(com.cloud.legacymodel.exceptions.InvalidParameterValueException) Filter(com.cloud.utils.db.Filter) List(java.util.List) Domain(com.cloud.legacymodel.domain.Domain) Pair(com.cloud.legacymodel.utils.Pair)

Example 20 with Domain

use of com.cloud.legacymodel.domain.Domain in project cosmic by MissionCriticalCloud.

the class AccountManagerImplTest method deleteUserAccount.

@Test
public void deleteUserAccount() {
    final AccountVO account = new AccountVO();
    account.setId(42l);
    final DomainVO domain = new DomainVO();
    Mockito.when(_accountDao.findById(42l)).thenReturn(account);
    Mockito.when(securityChecker.checkAccess(Mockito.any(Account.class), Mockito.any(ControlledEntity.class), Mockito.any(AccessType.class), Mockito.anyString())).thenReturn(true);
    Mockito.when(_accountDao.remove(42l)).thenReturn(true);
    Mockito.when(_configMgr.releaseAccountSpecificVirtualRanges(42l)).thenReturn(true);
    Mockito.when(_domainMgr.getDomain(Mockito.anyLong())).thenReturn(domain);
    Mockito.when(securityChecker.checkAccess(Mockito.any(Account.class), Mockito.any(Domain.class))).thenReturn(true);
    Mockito.when(_vmSnapshotDao.listByAccountId(Mockito.anyLong())).thenReturn(new ArrayList<>());
    Assert.assertTrue(accountManager.deleteUserAccount(42));
    // assert that this was a clean delete
    Mockito.verify(_accountDao, Mockito.never()).markForCleanup(Mockito.eq(42l));
}
Also used : DomainVO(com.cloud.domain.DomainVO) UserAccount(com.cloud.legacymodel.user.UserAccount) Account(com.cloud.legacymodel.user.Account) ControlledEntity(com.cloud.legacymodel.acl.ControlledEntity) Domain(com.cloud.legacymodel.domain.Domain) AccessType(com.cloud.acl.SecurityChecker.AccessType) Test(org.junit.Test)

Aggregations

Domain (com.cloud.legacymodel.domain.Domain)55 Account (com.cloud.legacymodel.user.Account)37 InvalidParameterValueException (com.cloud.legacymodel.exceptions.InvalidParameterValueException)20 UserAccount (com.cloud.legacymodel.user.UserAccount)19 ArrayList (java.util.ArrayList)16 PermissionDeniedException (com.cloud.legacymodel.exceptions.PermissionDeniedException)11 Project (com.cloud.projects.Project)11 DomainVO (com.cloud.domain.DomainVO)10 Network (com.cloud.legacymodel.network.Network)10 DomainResponse (com.cloud.api.response.DomainResponse)8 Pair (com.cloud.legacymodel.utils.Pair)7 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)7 HostVO (com.cloud.host.HostVO)6 List (java.util.List)6 Filter (com.cloud.utils.db.Filter)5 HashSet (java.util.HashSet)5 Test (org.junit.Test)5 AffinityGroupResponse (com.cloud.affinity.AffinityGroupResponse)4 CloudAuthenticationException (com.cloud.legacymodel.exceptions.CloudAuthenticationException)4 NetworkVO (com.cloud.network.dao.NetworkVO)4