Search in sources :

Example 46 with Filter

use of com.cloud.utils.db.Filter in project cloudstack by apache.

the class AsyncJobDaoImpl method getExpiredCompletedJobs.

@Override
public List<AsyncJobVO> getExpiredCompletedJobs(Date cutTime, int limit) {
    SearchCriteria<AsyncJobVO> sc = expiringCompletedAsyncJobSearch.create();
    sc.setParameters("created", cutTime);
    sc.setParameters("jobStatus", JobInfo.Status.IN_PROGRESS);
    Filter filter = new Filter(AsyncJobVO.class, "created", true, 0L, (long) limit);
    return listIncludingRemovedBy(sc, filter);
}
Also used : Filter(com.cloud.utils.db.Filter) AsyncJobVO(org.apache.cloudstack.framework.jobs.impl.AsyncJobVO)

Example 47 with Filter

use of com.cloud.utils.db.Filter in project cloudstack by apache.

the class QueryManagerImpl method searchForAsyncJobsInternal.

private Pair<List<AsyncJobJoinVO>, Integer> searchForAsyncJobsInternal(ListAsyncJobsCmd cmd) {
    Account caller = CallContext.current().getCallingAccount();
    List<Long> permittedAccounts = new ArrayList<Long>();
    Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
    Long domainId = domainIdRecursiveListProject.first();
    Boolean isRecursive = domainIdRecursiveListProject.second();
    ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    Filter searchFilter = new Filter(AsyncJobJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchBuilder<AsyncJobJoinVO> sb = _jobJoinDao.createSearchBuilder();
    sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN);
    boolean accountJoinIsDone = false;
    if (permittedAccounts.isEmpty() && domainId != null) {
        sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
        sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
        accountJoinIsDone = true;
    }
    if (listProjectResourcesCriteria != null) {
        if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) {
            sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.EQ);
        } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) {
            sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.NEQ);
        }
        if (!accountJoinIsDone) {
            sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
            sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
        }
    }
    Object keyword = cmd.getKeyword();
    Object startDate = cmd.getStartDate();
    SearchCriteria<AsyncJobJoinVO> sc = sb.create();
    if (listProjectResourcesCriteria != null) {
        sc.setParameters("type", Account.ACCOUNT_TYPE_PROJECT);
    }
    if (!permittedAccounts.isEmpty()) {
        sc.setParameters("accountIdIN", permittedAccounts.toArray());
    } else if (domainId != null) {
        DomainVO domain = _domainDao.findById(domainId);
        if (isRecursive) {
            sc.setParameters("path", domain.getPath() + "%");
        } else {
            sc.setParameters("domainId", domainId);
        }
    }
    if (keyword != null) {
        sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%");
    }
    if (startDate != null) {
        sc.addAnd("created", SearchCriteria.Op.GTEQ, startDate);
    }
    return _jobJoinDao.searchAndCount(sc, searchFilter);
}
Also used : Account(com.cloud.user.Account) Ternary(com.cloud.utils.Ternary) ArrayList(java.util.ArrayList) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) DomainVO(com.cloud.domain.DomainVO) AsyncJobJoinVO(com.cloud.api.query.vo.AsyncJobJoinVO) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter)

Example 48 with Filter

use of com.cloud.utils.db.Filter in project cloudstack by apache.

the class QueryManagerImpl method searchForUserVMsInternal.

private Pair<List<UserVmJoinVO>, Integer> searchForUserVMsInternal(ListVMsCmd cmd) {
    Account caller = CallContext.current().getCallingAccount();
    List<Long> permittedAccounts = new ArrayList<Long>();
    boolean listAll = cmd.listAll();
    Long id = cmd.getId();
    Long userId = cmd.getUserId();
    Map<String, String> tags = cmd.getTags();
    Boolean display = cmd.getDisplay();
    Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false);
    Long domainId = domainIdRecursiveListProject.first();
    Boolean isRecursive = domainIdRecursiveListProject.second();
    ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    Filter searchFilter = new Filter(UserVmJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    List<Long> ids = null;
    if (cmd.getId() != null) {
        if (cmd.getIds() != null && !cmd.getIds().isEmpty()) {
            throw new InvalidParameterValueException("Specify either id or ids but not both parameters");
        }
        ids = new ArrayList<Long>();
        ids.add(cmd.getId());
    } else {
        ids = cmd.getIds();
    }
    // first search distinct vm id by using query criteria and pagination
    SearchBuilder<UserVmJoinVO> sb = _userVmJoinDao.createSearchBuilder();
    // select distinct ids
    sb.select(null, Func.DISTINCT, sb.entity().getId());
    _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    String hypervisor = cmd.getHypervisor();
    Object name = cmd.getName();
    String state = cmd.getState();
    Object zoneId = cmd.getZoneId();
    Object keyword = cmd.getKeyword();
    boolean isAdmin = false;
    boolean isRootAdmin = false;
    if (_accountMgr.isAdmin(caller.getId())) {
        isAdmin = true;
    }
    if (_accountMgr.isRootAdmin(caller.getId())) {
        isRootAdmin = true;
    }
    Object groupId = cmd.getGroupId();
    Object networkId = cmd.getNetworkId();
    if (HypervisorType.getType(hypervisor) == HypervisorType.None && hypervisor != null) {
        // invalid hypervisor type input
        throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor);
    }
    Object templateId = cmd.getTemplateId();
    Object isoId = cmd.getIsoId();
    Object vpcId = cmd.getVpcId();
    Object affinityGroupId = cmd.getAffinityGroupId();
    Object keyPairName = cmd.getKeyPairName();
    Object serviceOffId = cmd.getServiceOfferingId();
    Object pod = null;
    Object hostId = null;
    Object storageId = null;
    if (cmd instanceof ListVMsCmdByAdmin) {
        ListVMsCmdByAdmin adCmd = (ListVMsCmdByAdmin) cmd;
        pod = adCmd.getPodId();
        hostId = adCmd.getHostId();
        storageId = adCmd.getStorageId();
    }
    sb.and("displayName", sb.entity().getDisplayName(), SearchCriteria.Op.LIKE);
    sb.and("idIN", sb.entity().getId(), SearchCriteria.Op.IN);
    sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
    sb.and("stateEQ", sb.entity().getState(), SearchCriteria.Op.EQ);
    sb.and("stateNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ);
    sb.and("stateNIN", sb.entity().getState(), SearchCriteria.Op.NIN);
    sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
    sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
    sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ);
    sb.and("hostIdEQ", sb.entity().getHostId(), SearchCriteria.Op.EQ);
    sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ);
    sb.and("isoId", sb.entity().getIsoId(), SearchCriteria.Op.EQ);
    sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ);
    if (serviceOffId != null) {
        sb.and("serviceOfferingId", sb.entity().getServiceOfferingId(), SearchCriteria.Op.EQ);
    }
    if (display != null) {
        sb.and("display", sb.entity().isDisplayVm(), SearchCriteria.Op.EQ);
    }
    if (groupId != null && (Long) groupId != -1) {
        sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ);
    }
    if (userId != null) {
        sb.and("userId", sb.entity().getUserId(), SearchCriteria.Op.EQ);
    }
    if (networkId != null) {
        sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ);
    }
    if (vpcId != null && networkId == null) {
        sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ);
    }
    if (storageId != null) {
        sb.and("poolId", sb.entity().getPoolId(), SearchCriteria.Op.EQ);
    }
    if (affinityGroupId != null) {
        sb.and("affinityGroupId", sb.entity().getAffinityGroupId(), SearchCriteria.Op.EQ);
    }
    if (keyPairName != null) {
        sb.and("keyPairName", sb.entity().getKeypairName(), SearchCriteria.Op.EQ);
    }
    if (!isRootAdmin) {
        sb.and("displayVm", sb.entity().isDisplayVm(), SearchCriteria.Op.EQ);
    }
    // populate the search criteria with the values passed in
    SearchCriteria<UserVmJoinVO> sc = sb.create();
    // building ACL condition
    _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    if (tags != null && !tags.isEmpty()) {
        SearchCriteria<UserVmJoinVO> tagSc = _userVmJoinDao.createSearchCriteria();
        for (Map.Entry<String, String> entry : tags.entrySet()) {
            SearchCriteria<UserVmJoinVO> tsc = _userVmJoinDao.createSearchCriteria();
            tsc.addAnd("tagKey", SearchCriteria.Op.EQ, entry.getKey());
            tsc.addAnd("tagValue", SearchCriteria.Op.EQ, entry.getValue());
            tagSc.addOr("tagKey", SearchCriteria.Op.SC, tsc);
        }
        sc.addAnd("tagKey", SearchCriteria.Op.SC, tagSc);
    }
    if (groupId != null && (Long) groupId != -1) {
        sc.setParameters("instanceGroupId", groupId);
    }
    if (keyword != null) {
        SearchCriteria<UserVmJoinVO> ssc = _userVmJoinDao.createSearchCriteria();
        ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("state", SearchCriteria.Op.EQ, keyword);
        sc.addAnd("displayName", SearchCriteria.Op.SC, ssc);
    }
    if (serviceOffId != null) {
        sc.setParameters("serviceOfferingId", serviceOffId);
    }
    if (display != null) {
        sc.setParameters("display", display);
    }
    if (ids != null && !ids.isEmpty()) {
        sc.setParameters("idIN", ids.toArray());
    }
    if (templateId != null) {
        sc.setParameters("templateId", templateId);
    }
    if (isoId != null) {
        sc.setParameters("isoId", isoId);
    }
    if (userId != null) {
        sc.setParameters("userId", userId);
    }
    if (networkId != null) {
        sc.setParameters("networkId", networkId);
    }
    if (vpcId != null && networkId == null) {
        sc.setParameters("vpcId", vpcId);
    }
    if (name != null) {
        sc.setParameters("name", "%" + name + "%");
    }
    if (state != null) {
        if (state.equalsIgnoreCase("present")) {
            sc.setParameters("stateNIN", "Destroyed", "Expunging");
        } else {
            sc.setParameters("stateEQ", state);
        }
    }
    if (hypervisor != null) {
        sc.setParameters("hypervisorType", hypervisor);
    }
    // Don't show Destroyed and Expunging vms to the end user if the AllowUserViewDestroyedVM flag is not set.
    if (!isAdmin && !AllowUserViewDestroyedVM.valueIn(caller.getAccountId())) {
        sc.setParameters("stateNIN", "Destroyed", "Expunging");
    }
    if (zoneId != null) {
        sc.setParameters("dataCenterId", zoneId);
    }
    if (affinityGroupId != null) {
        sc.setParameters("affinityGroupId", affinityGroupId);
    }
    if (keyPairName != null) {
        sc.setParameters("keyPairName", keyPairName);
    }
    if (cmd instanceof ListVMsCmdByAdmin) {
        ListVMsCmdByAdmin aCmd = (ListVMsCmdByAdmin) cmd;
        if (aCmd.getPodId() != null) {
            sc.setParameters("podId", pod);
            if (state == null) {
                sc.setParameters("stateNEQ", "Destroyed");
            }
        }
        if (hostId != null) {
            sc.setParameters("hostIdEQ", hostId);
        }
        if (storageId != null) {
            sc.setParameters("poolId", storageId);
        }
    }
    if (!isRootAdmin) {
        sc.setParameters("displayVm", 1);
    }
    // search vm details by ids
    Pair<List<UserVmJoinVO>, Integer> uniqueVmPair = _userVmJoinDao.searchAndDistinctCount(sc, searchFilter);
    Integer count = uniqueVmPair.second();
    if (count.intValue() == 0) {
        // handle empty result cases
        return uniqueVmPair;
    }
    List<UserVmJoinVO> uniqueVms = uniqueVmPair.first();
    Long[] vmIds = new Long[uniqueVms.size()];
    int i = 0;
    for (UserVmJoinVO v : uniqueVms) {
        vmIds[i++] = v.getId();
    }
    List<UserVmJoinVO> vms = _userVmJoinDao.searchByIds(vmIds);
    return new Pair<List<UserVmJoinVO>, Integer>(vms, count);
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair) Ternary(com.cloud.utils.Ternary) UserVmJoinVO(com.cloud.api.query.vo.UserVmJoinVO) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) ListVMsCmdByAdmin(org.apache.cloudstack.api.command.admin.vm.ListVMsCmdByAdmin) Map(java.util.Map)

Example 49 with Filter

use of com.cloud.utils.db.Filter in project cloudstack by apache.

the class QueryManagerImpl method searchForDiskOfferingsInternal.

private Pair<List<DiskOfferingJoinVO>, Integer> searchForDiskOfferingsInternal(ListDiskOfferingsCmd cmd) {
    // Note
    // The list method for offerings is being modified in accordance with
    // discussion with Will/Kevin
    // For now, we will be listing the following based on the usertype
    // 1. For root, we will list all offerings
    // 2. For domainAdmin and regular users, we will list everything in
    // their domains+parent domains ... all the way
    // till
    // root
    Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
    isAscending = (isAscending == null ? true : isAscending);
    Filter searchFilter = new Filter(DiskOfferingJoinVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchCriteria<DiskOfferingJoinVO> sc = _diskOfferingJoinDao.createSearchCriteria();
    sc.addAnd("type", Op.EQ, DiskOfferingVO.Type.Disk);
    Account account = CallContext.current().getCallingAccount();
    Object name = cmd.getDiskOfferingName();
    Object id = cmd.getId();
    Object keyword = cmd.getKeyword();
    Long domainId = cmd.getDomainId();
    Boolean isRootAdmin = _accountMgr.isRootAdmin(account.getAccountId());
    Boolean isRecursive = cmd.isRecursive();
    // associated with this domain
    if (domainId != null) {
        if (_accountMgr.isRootAdmin(account.getId()) || isPermissible(account.getDomainId(), domainId)) {
            // check if the user's domain == do's domain || user's domain is
            // a child of so's domain for non-root users
            sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
            if (!isRootAdmin) {
                sc.addAnd("displayOffering", SearchCriteria.Op.EQ, 1);
            }
            return _diskOfferingJoinDao.searchAndCount(sc, searchFilter);
        } else {
            throw new PermissionDeniedException("The account:" + account.getAccountName() + " does not fall in the same domain hierarchy as the disk offering");
        }
    }
    List<Long> domainIds = null;
    // and everything above till root
    if ((_accountMgr.isNormalUser(account.getId()) || _accountMgr.isDomainAdmin(account.getId())) || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
        if (isRecursive) {
            // domain + all sub-domains
            if (account.getType() == Account.ACCOUNT_TYPE_NORMAL)
                throw new InvalidParameterValueException("Only ROOT admins and Domain admins can list disk offerings with isrecursive=true");
            DomainVO domainRecord = _domainDao.findById(account.getDomainId());
            sc.addAnd("domainPath", SearchCriteria.Op.LIKE, domainRecord.getPath() + "%");
        } else {
            // domain + all ancestors
            // find all domain Id up to root domain for this account
            domainIds = new ArrayList<Long>();
            DomainVO domainRecord = _domainDao.findById(account.getDomainId());
            if (domainRecord == null) {
                s_logger.error("Could not find the domainId for account:" + account.getAccountName());
                throw new CloudAuthenticationException("Could not find the domainId for account:" + account.getAccountName());
            }
            domainIds.add(domainRecord.getId());
            while (domainRecord.getParent() != null) {
                domainRecord = _domainDao.findById(domainRecord.getParent());
                domainIds.add(domainRecord.getId());
            }
            SearchCriteria<DiskOfferingJoinVO> spc = _diskOfferingJoinDao.createSearchCriteria();
            spc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
            // include public offering as where
            spc.addOr("domainId", SearchCriteria.Op.NULL);
            sc.addAnd("domainId", SearchCriteria.Op.SC, spc);
            // non-root users should not see system offering at all
            sc.addAnd("systemUse", SearchCriteria.Op.EQ, false);
        }
    }
    if (keyword != null) {
        SearchCriteria<DiskOfferingJoinVO> ssc = _diskOfferingJoinDao.createSearchCriteria();
        ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    if (id != null) {
        sc.addAnd("id", SearchCriteria.Op.EQ, id);
    }
    if (name != null) {
        sc.addAnd("name", SearchCriteria.Op.EQ, name);
    }
    return _diskOfferingJoinDao.searchAndCount(sc, searchFilter);
}
Also used : Account(com.cloud.user.Account) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) DiskOfferingJoinVO(com.cloud.api.query.vo.DiskOfferingJoinVO) DomainVO(com.cloud.domain.DomainVO) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException)

Example 50 with Filter

use of com.cloud.utils.db.Filter in project cloudstack by apache.

the class QueryManagerImpl method searchForTemplatesInternal.

private Pair<List<TemplateJoinVO>, Integer> searchForTemplatesInternal(Long templateId, String name, String keyword, TemplateFilter templateFilter, boolean isIso, Boolean bootable, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady, List<Account> permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria, Map<String, String> tags, boolean showRemovedTmpl, List<Long> ids) {
    // check if zone is configured, if not, just return empty list
    List<HypervisorType> hypers = null;
    if (!isIso) {
        hypers = _resourceMgr.listAvailHypervisorInZone(null, null);
        if (hypers == null || hypers.isEmpty()) {
            return new Pair<List<TemplateJoinVO>, Integer>(new ArrayList<TemplateJoinVO>(), 0);
        }
    }
    VMTemplateVO template = null;
    Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
    isAscending = (isAscending == null ? Boolean.TRUE : isAscending);
    Filter searchFilter = new Filter(TemplateJoinVO.class, "sortKey", isAscending, startIndex, pageSize);
    searchFilter.addOrderBy(TemplateJoinVO.class, "tempZonePair", isAscending);
    SearchBuilder<TemplateJoinVO> sb = _templateJoinDao.createSearchBuilder();
    // select distinct (templateId, zoneId) pair
    sb.select(null, Func.DISTINCT, sb.entity().getTempZonePair());
    if (ids != null && !ids.isEmpty()) {
        sb.and("idIN", sb.entity().getId(), SearchCriteria.Op.IN);
    }
    SearchCriteria<TemplateJoinVO> sc = sb.create();
    // verify templateId parameter and specially handle it
    if (templateId != null) {
        // Done for backward compatibility - Bug-5221
        template = _templateDao.findByIdIncludingRemoved(templateId);
        if (template == null) {
            throw new InvalidParameterValueException("Please specify a valid template ID.");
        }
        // If ISO requested then it should be ISO.
        if (isIso && template.getFormat() != ImageFormat.ISO) {
            s_logger.error("Template Id " + templateId + " is not an ISO");
            InvalidParameterValueException ex = new InvalidParameterValueException("Specified Template Id is not an ISO");
            ex.addProxyObject(template.getUuid(), "templateId");
            throw ex;
        }
        // If ISO not requested then it shouldn't be an ISO.
        if (!isIso && template.getFormat() == ImageFormat.ISO) {
            s_logger.error("Incorrect format of the template id " + templateId);
            InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format " + template.getFormat() + " of the specified template id");
            ex.addProxyObject(template.getUuid(), "templateId");
            throw ex;
        }
        if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) {
            Account template_acc = _accountMgr.getAccount(template.getAccountId());
            DomainVO domain = _domainDao.findById(template_acc.getDomainId());
            _accountMgr.checkAccess(caller, domain);
        } else // if template is not public, perform permission check here
        if (!template.isPublicTemplate() && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            _accountMgr.checkAccess(caller, null, false, template);
        }
        // if templateId is specified, then we will just use the id to
        // search and ignore other query parameters
        sc.addAnd("id", SearchCriteria.Op.EQ, templateId);
    } else {
        DomainVO domain = null;
        if (!permittedAccounts.isEmpty()) {
            domain = _domainDao.findById(permittedAccounts.get(0).getDomainId());
        } else {
            domain = _domainDao.findById(Domain.ROOT_DOMAIN);
        }
        // List<HypervisorType> hypers = null;
        // if (!isIso) {
        // hypers = _resourceMgr.listAvailHypervisorInZone(null, null);
        // }
        setIdsListToSearchCriteria(sc, ids);
        // add criteria for project or not
        if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
            sc.addAnd("accountType", SearchCriteria.Op.NEQ, Account.ACCOUNT_TYPE_PROJECT);
        } else if (listProjectResourcesCriteria == ListProjectResourcesCriteria.ListProjectResourcesOnly) {
            sc.addAnd("accountType", SearchCriteria.Op.EQ, Account.ACCOUNT_TYPE_PROJECT);
        }
        // add criteria for domain path in case of domain admin
        if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) && (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN)) {
            sc.addAnd("domainPath", SearchCriteria.Op.LIKE, domain.getPath() + "%");
        }
        List<Long> relatedDomainIds = new ArrayList<Long>();
        List<Long> permittedAccountIds = new ArrayList<Long>();
        if (!permittedAccounts.isEmpty()) {
            for (Account account : permittedAccounts) {
                permittedAccountIds.add(account.getId());
                boolean publicTemplates = (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community);
                // get all parent domain ID's all the way till root domain
                DomainVO domainTreeNode = null;
                //if template filter is featured, or community, all child domains should be included in search
                if (publicTemplates) {
                    domainTreeNode = _domainDao.findById(Domain.ROOT_DOMAIN);
                } else {
                    domainTreeNode = _domainDao.findById(account.getDomainId());
                }
                relatedDomainIds.add(domainTreeNode.getId());
                while (domainTreeNode.getParent() != null) {
                    domainTreeNode = _domainDao.findById(domainTreeNode.getParent());
                    relatedDomainIds.add(domainTreeNode.getId());
                }
                // get all child domain ID's
                if (_accountMgr.isAdmin(account.getId()) || publicTemplates) {
                    List<DomainVO> allChildDomains = _domainDao.findAllChildren(domainTreeNode.getPath(), domainTreeNode.getId());
                    for (DomainVO childDomain : allChildDomains) {
                        relatedDomainIds.add(childDomain.getId());
                    }
                }
            }
        }
        if (!isIso) {
            // add hypervisor criteria for template case
            if (hypers != null && !hypers.isEmpty()) {
                String[] relatedHypers = new String[hypers.size()];
                for (int i = 0; i < hypers.size(); i++) {
                    relatedHypers[i] = hypers.get(i).toString();
                }
                sc.addAnd("hypervisorType", SearchCriteria.Op.IN, relatedHypers);
            }
        }
        // control different template filters
        if (templateFilter == TemplateFilter.featured || templateFilter == TemplateFilter.community) {
            sc.addAnd("publicTemplate", SearchCriteria.Op.EQ, true);
            if (templateFilter == TemplateFilter.featured) {
                sc.addAnd("featured", SearchCriteria.Op.EQ, true);
            } else {
                sc.addAnd("featured", SearchCriteria.Op.EQ, false);
            }
            if (!permittedAccounts.isEmpty()) {
                SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
                scc.addOr("domainId", SearchCriteria.Op.IN, relatedDomainIds.toArray());
                scc.addOr("domainId", SearchCriteria.Op.NULL);
                sc.addAnd("domainId", SearchCriteria.Op.SC, scc);
            }
        } else if (templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) {
            if (!permittedAccounts.isEmpty()) {
                sc.addAnd("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
            }
        } else if (templateFilter == TemplateFilter.sharedexecutable || templateFilter == TemplateFilter.shared) {
            // only show templates shared by others
            sc.addAnd("sharedAccountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
        } else if (templateFilter == TemplateFilter.executable) {
            SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
            scc.addOr("publicTemplate", SearchCriteria.Op.EQ, true);
            if (!permittedAccounts.isEmpty()) {
                scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
            }
            sc.addAnd("publicTemplate", SearchCriteria.Op.SC, scc);
        } else if (templateFilter == TemplateFilter.all && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
            scc.addOr("publicTemplate", SearchCriteria.Op.EQ, true);
            if (listProjectResourcesCriteria == ListProjectResourcesCriteria.SkipProjectResources) {
                scc.addOr("domainPath", SearchCriteria.Op.LIKE, _domainDao.findById(caller.getDomainId()).getPath() + "%");
            } else {
                if (!permittedAccounts.isEmpty()) {
                    scc.addOr("accountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
                    scc.addOr("sharedAccountId", SearchCriteria.Op.IN, permittedAccountIds.toArray());
                }
            }
            sc.addAnd("publicTemplate", SearchCriteria.Op.SC, scc);
        }
        // add tags criteria
        if (tags != null && !tags.isEmpty()) {
            SearchCriteria<TemplateJoinVO> scc = _templateJoinDao.createSearchCriteria();
            for (Map.Entry<String, String> entry : tags.entrySet()) {
                SearchCriteria<TemplateJoinVO> scTag = _templateJoinDao.createSearchCriteria();
                scTag.addAnd("tagKey", SearchCriteria.Op.EQ, entry.getKey());
                scTag.addAnd("tagValue", SearchCriteria.Op.EQ, entry.getValue());
                if (isIso) {
                    scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, ResourceObjectType.ISO);
                } else {
                    scTag.addAnd("tagResourceType", SearchCriteria.Op.EQ, ResourceObjectType.Template);
                }
                scc.addOr("tagKey", SearchCriteria.Op.SC, scTag);
            }
            sc.addAnd("tagKey", SearchCriteria.Op.SC, scc);
        }
        if (keyword != null) {
            sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        } else if (name != null) {
            sc.addAnd("name", SearchCriteria.Op.EQ, name);
        }
        if (isIso) {
            sc.addAnd("format", SearchCriteria.Op.EQ, "ISO");
        } else {
            sc.addAnd("format", SearchCriteria.Op.NEQ, "ISO");
        }
        if (!hyperType.equals(HypervisorType.None)) {
            sc.addAnd("hypervisorType", SearchCriteria.Op.EQ, hyperType);
        }
        if (bootable != null) {
            sc.addAnd("bootable", SearchCriteria.Op.EQ, bootable);
        }
        if (onlyReady) {
            SearchCriteria<TemplateJoinVO> readySc = _templateJoinDao.createSearchCriteria();
            readySc.addOr("state", SearchCriteria.Op.EQ, TemplateState.Ready);
            readySc.addOr("format", SearchCriteria.Op.EQ, ImageFormat.BAREMETAL);
            SearchCriteria<TemplateJoinVO> isoPerhostSc = _templateJoinDao.createSearchCriteria();
            isoPerhostSc.addAnd("format", SearchCriteria.Op.EQ, ImageFormat.ISO);
            isoPerhostSc.addAnd("templateType", SearchCriteria.Op.EQ, TemplateType.PERHOST);
            readySc.addOr("templateType", SearchCriteria.Op.SC, isoPerhostSc);
            sc.addAnd("state", SearchCriteria.Op.SC, readySc);
        }
        if (!showDomr) {
            // excluding system template
            sc.addAnd("templateType", SearchCriteria.Op.NEQ, Storage.TemplateType.SYSTEM);
        }
    }
    if (zoneId != null) {
        SearchCriteria<TemplateJoinVO> zoneSc = _templateJoinDao.createSearchCriteria();
        zoneSc.addOr("dataCenterId", SearchCriteria.Op.EQ, zoneId);
        zoneSc.addOr("dataStoreScope", SearchCriteria.Op.EQ, ScopeType.REGION);
        // handle the case where xs-tools.iso and vmware-tools.iso do not
        // have data_center information in template_view
        SearchCriteria<TemplateJoinVO> isoPerhostSc = _templateJoinDao.createSearchCriteria();
        isoPerhostSc.addAnd("format", SearchCriteria.Op.EQ, ImageFormat.ISO);
        isoPerhostSc.addAnd("templateType", SearchCriteria.Op.EQ, TemplateType.PERHOST);
        zoneSc.addOr("templateType", SearchCriteria.Op.SC, isoPerhostSc);
        sc.addAnd("dataCenterId", SearchCriteria.Op.SC, zoneSc);
    }
    // don't return removed template, this should not be needed since we
    // changed annotation for removed field in TemplateJoinVO.
    // sc.addAnd("removed", SearchCriteria.Op.NULL);
    // search unique templates and find details by Ids
    Pair<List<TemplateJoinVO>, Integer> uniqueTmplPair = null;
    if (showRemovedTmpl) {
        uniqueTmplPair = _templateJoinDao.searchIncludingRemovedAndCount(sc, searchFilter);
    } else {
        sc.addAnd("templateState", SearchCriteria.Op.IN, new State[] { State.Active, State.NotUploaded, State.UploadInProgress });
        uniqueTmplPair = _templateJoinDao.searchAndCount(sc, searchFilter);
    }
    Integer count = uniqueTmplPair.second();
    if (count.intValue() == 0) {
        // empty result
        return uniqueTmplPair;
    }
    List<TemplateJoinVO> uniqueTmpls = uniqueTmplPair.first();
    String[] tzIds = new String[uniqueTmpls.size()];
    int i = 0;
    for (TemplateJoinVO v : uniqueTmpls) {
        tzIds[i++] = v.getTempZonePair();
    }
    List<TemplateJoinVO> vrs = _templateJoinDao.searchByTemplateZonePair(showRemovedTmpl, tzIds);
    return new Pair<List<TemplateJoinVO>, Integer>(vrs, count);
// TODO: revisit the special logic for iso search in
// VMTemplateDaoImpl.searchForTemplates and understand why we need to
// specially handle ISO. The original logic is very twisted and no idea
// about what the code was doing.
}
Also used : Account(com.cloud.user.Account) VMTemplateVO(com.cloud.storage.VMTemplateVO) ArrayList(java.util.ArrayList) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TemplateJoinVO(com.cloud.api.query.vo.TemplateJoinVO) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair) SearchCriteria(com.cloud.utils.db.SearchCriteria) HypervisorType(com.cloud.hypervisor.Hypervisor.HypervisorType) DomainVO(com.cloud.domain.DomainVO) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) Map(java.util.Map)

Aggregations

Filter (com.cloud.utils.db.Filter)114 ArrayList (java.util.ArrayList)68 List (java.util.List)64 Pair (com.cloud.utils.Pair)58 Account (com.cloud.user.Account)46 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)33 ListProjectResourcesCriteria (com.cloud.projects.Project.ListProjectResourcesCriteria)30 Ternary (com.cloud.utils.Ternary)30 TemplateFilter (com.cloud.template.VirtualMachineTemplate.TemplateFilter)27 DomainVO (com.cloud.domain.DomainVO)13 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)12 SSHKeyPair (com.cloud.user.SSHKeyPair)12 ResourceTagVO (com.cloud.tags.ResourceTagVO)11 Date (java.util.Date)10 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)9 IPAddressVO (com.cloud.network.dao.IPAddressVO)8 VMTemplateVO (com.cloud.storage.VMTemplateVO)5 SearchCriteria (com.cloud.utils.db.SearchCriteria)5 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)5 CloudAuthenticationException (com.cloud.exception.CloudAuthenticationException)4