Search in sources :

Example 1 with Filter

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

the class QuotaServiceImpl method findQuotaBalanceVO.

@Override
public List<QuotaBalanceVO> findQuotaBalanceVO(Long accountId, String accountName, Long domainId, Date startDate, Date endDate) {
    if ((accountId == null) && (accountName != null) && (domainId != null)) {
        Account userAccount = null;
        Account caller = CallContext.current().getCallingAccount();
        if (_domainDao.isChildDomain(caller.getDomainId(), domainId)) {
            Filter filter = new Filter(AccountVO.class, "id", Boolean.FALSE, null, null);
            List<AccountVO> accounts = _accountDao.listAccounts(accountName, domainId, filter);
            if (!accounts.isEmpty()) {
                userAccount = accounts.get(0);
            }
            if (userAccount != null) {
                accountId = userAccount.getId();
            } else {
                throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
            }
        } else {
            throw new PermissionDeniedException("Invalid Domain Id or Account");
        }
    }
    startDate = startDate == null ? new Date() : startDate;
    if (endDate == null) {
        // adjust start date to end of day as there is no end date
        Date adjustedStartDate = computeAdjustedTime(_respBldr.startOfNextDay(startDate));
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("getQuotaBalance1: Getting quota balance records for account: " + accountId + ", domainId: " + domainId + ", on or before " + adjustedStartDate);
        }
        List<QuotaBalanceVO> qbrecords = _quotaBalanceDao.lastQuotaBalanceVO(accountId, domainId, adjustedStartDate);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Found records size=" + qbrecords.size());
        }
        if (qbrecords.isEmpty()) {
            s_logger.info("Incorrect Date there are no quota records before this date " + adjustedStartDate);
            return qbrecords;
        } else {
            return qbrecords;
        }
    } else {
        Date adjustedStartDate = computeAdjustedTime(startDate);
        if (endDate.after(_respBldr.startOfNextDay())) {
            throw new InvalidParameterValueException("Incorrect Date Range. End date:" + endDate + " should not be in future. ");
        } else if (startDate.before(endDate)) {
            Date adjustedEndDate = computeAdjustedTime(endDate);
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("getQuotaBalance2: Getting quota balance records for account: " + accountId + ", domainId: " + domainId + ", between " + adjustedStartDate + " and " + adjustedEndDate);
            }
            List<QuotaBalanceVO> qbrecords = _quotaBalanceDao.findQuotaBalance(accountId, domainId, adjustedStartDate, adjustedEndDate);
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("getQuotaBalance3: Found records size=" + qbrecords.size());
            }
            if (qbrecords.isEmpty()) {
                s_logger.info("There are no quota records between these dates start date " + adjustedStartDate + " and end date:" + endDate);
                return qbrecords;
            } else {
                return qbrecords;
            }
        } else {
            throw new InvalidParameterValueException("Incorrect Date Range. Start date: " + startDate + " is after end date:" + endDate);
        }
    }
}
Also used : Account(com.cloud.user.Account) Filter(com.cloud.utils.db.Filter) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) QuotaBalanceVO(org.apache.cloudstack.quota.vo.QuotaBalanceVO) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ArrayList(java.util.ArrayList) List(java.util.List) QuotaAccountVO(org.apache.cloudstack.quota.vo.QuotaAccountVO) AccountVO(com.cloud.user.AccountVO) Date(java.util.Date)

Example 2 with Filter

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

the class TemplateJoinDaoImpl method searchByTemplateZonePair.

@Override
public List<TemplateJoinVO> searchByTemplateZonePair(Boolean showRemoved, String... idPairs) {
    // set detail batch query size
    int DETAILS_BATCH_SIZE = 2000;
    String batchCfg = _configDao.getValue("detail.batch.query.size");
    if (batchCfg != null) {
        DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg);
    }
    // query details by batches
    Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
    isAscending = (isAscending == null ? Boolean.TRUE : isAscending);
    Filter searchFilter = new Filter(TemplateJoinVO.class, "sortKey", isAscending, null, null);
    searchFilter.addOrderBy(TemplateJoinVO.class, "tempZonePair", isAscending);
    List<TemplateJoinVO> uvList = new ArrayList<TemplateJoinVO>();
    // query details by batches
    int curr_index = 0;
    if (idPairs.length > DETAILS_BATCH_SIZE) {
        while ((curr_index + DETAILS_BATCH_SIZE) <= idPairs.length) {
            String[] labels = new String[DETAILS_BATCH_SIZE];
            for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) {
                labels[k] = idPairs[j];
            }
            SearchCriteria<TemplateJoinVO> sc = tmpltIdPairSearch.create();
            if (!showRemoved) {
                sc.setParameters("templateState", VirtualMachineTemplate.State.Active);
            }
            sc.setParameters("tempZonePairIN", labels);
            List<TemplateJoinVO> vms = searchIncludingRemoved(sc, searchFilter, null, false);
            if (vms != null) {
                uvList.addAll(vms);
            }
            curr_index += DETAILS_BATCH_SIZE;
        }
    }
    if (curr_index < idPairs.length) {
        int batch_size = (idPairs.length - curr_index);
        String[] labels = new String[batch_size];
        for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) {
            labels[k] = idPairs[j];
        }
        SearchCriteria<TemplateJoinVO> sc = tmpltIdPairSearch.create();
        if (!showRemoved) {
            sc.setParameters("templateState", VirtualMachineTemplate.State.Active, VirtualMachineTemplate.State.NotUploaded, VirtualMachineTemplate.State.UploadInProgress);
        }
        sc.setParameters("tempZonePairIN", labels);
        List<TemplateJoinVO> vms = searchIncludingRemoved(sc, searchFilter, null, false);
        if (vms != null) {
            uvList.addAll(vms);
        }
    }
    return uvList;
}
Also used : Filter(com.cloud.utils.db.Filter) ArrayList(java.util.ArrayList) TemplateJoinVO(com.cloud.api.query.vo.TemplateJoinVO)

Example 3 with Filter

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

the class ConfigurationManagerImpl method listNetworkOfferings.

@Override
public List<? extends NetworkOffering> listNetworkOfferings(final TrafficType trafficType, final boolean systemOnly) {
    final Filter searchFilter = new Filter(NetworkOfferingVO.class, "created", false, null, null);
    final SearchCriteria<NetworkOfferingVO> sc = _networkOfferingDao.createSearchCriteria();
    if (trafficType != null) {
        sc.addAnd("trafficType", SearchCriteria.Op.EQ, trafficType);
    }
    sc.addAnd("systemOnly", SearchCriteria.Op.EQ, systemOnly);
    return _networkOfferingDao.search(sc, searchFilter);
}
Also used : Filter(com.cloud.utils.db.Filter) NetworkOfferingVO(com.cloud.offerings.NetworkOfferingVO)

Example 4 with Filter

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

the class FirewallManagerImpl method listFirewallRules.

@Override
public Pair<List<? extends FirewallRule>, Integer> listFirewallRules(IListFirewallRulesCmd cmd) {
    Long ipId = cmd.getIpAddressId();
    Long id = cmd.getId();
    Long networkId = cmd.getNetworkId();
    Map<String, String> tags = cmd.getTags();
    FirewallRule.TrafficType trafficType = cmd.getTrafficType();
    Boolean display = cmd.getDisplay();
    Account caller = CallContext.current().getCallingAccount();
    List<Long> permittedAccounts = new ArrayList<Long>();
    if (ipId != null) {
        IPAddressVO ipAddressVO = _ipAddressDao.findById(ipId);
        if (ipAddressVO == null || !ipAddressVO.readyToUse()) {
            throw new InvalidParameterValueException("Ip address id=" + ipId + " not ready for firewall rules yet");
        }
        _accountMgr.checkAccess(caller, null, true, ipAddressVO);
    }
    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, cmd.listAll(), false);
    Long domainId = domainIdRecursiveListProject.first();
    Boolean isRecursive = domainIdRecursiveListProject.second();
    ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    Filter filter = new Filter(FirewallRuleVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchBuilder<FirewallRuleVO> sb = _firewallDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sb.and("id", sb.entity().getId(), Op.EQ);
    sb.and("trafficType", sb.entity().getTrafficType(), Op.EQ);
    sb.and("networkId", sb.entity().getNetworkId(), Op.EQ);
    sb.and("ip", sb.entity().getSourceIpAddressId(), Op.EQ);
    sb.and("purpose", sb.entity().getPurpose(), Op.EQ);
    sb.and("display", sb.entity().isDisplay(), Op.EQ);
    if (tags != null && !tags.isEmpty()) {
        SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
        for (int count = 0; count < tags.size(); count++) {
            tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ);
            tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ);
            tagSearch.cp();
        }
        tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ);
        sb.groupBy(sb.entity().getId());
        sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
    }
    SearchCriteria<FirewallRuleVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (tags != null && !tags.isEmpty()) {
        int count = 0;
        sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.FirewallRule.toString());
        for (String key : tags.keySet()) {
            sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
            sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
            count++;
        }
    }
    if (display != null) {
        sc.setParameters("display", display);
    }
    if (ipId != null) {
        sc.setParameters("ip", ipId);
    }
    if (networkId != null) {
        sc.setParameters("networkId", networkId);
    }
    sc.setParameters("purpose", Purpose.Firewall);
    sc.setParameters("trafficType", trafficType);
    Pair<List<FirewallRuleVO>, Integer> result = _firewallDao.searchAndCount(sc, filter);
    return new Pair<List<? extends FirewallRule>, Integer>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceTagVO(com.cloud.tags.ResourceTagVO) List(java.util.List) ArrayList(java.util.ArrayList) FirewallRule(com.cloud.network.rules.FirewallRule) Pair(com.cloud.utils.Pair) Ternary(com.cloud.utils.Ternary) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) Filter(com.cloud.utils.db.Filter) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 5 with Filter

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

the class ResourceLimitManagerImpl method searchForLimits.

@Override
public List<ResourceLimitVO> searchForLimits(Long id, Long accountId, Long domainId, Integer type, Long startIndex, Long pageSizeVal) {
    Account caller = CallContext.current().getCallingAccount();
    List<ResourceLimitVO> limits = new ArrayList<ResourceLimitVO>();
    boolean isAccount = true;
    if (!_accountMgr.isAdmin(caller.getId())) {
        accountId = caller.getId();
        domainId = null;
    } else {
        if (domainId != null) {
            // verify domain information and permissions
            Domain domain = _domainDao.findById(domainId);
            if (domain == null) {
                // return empty set
                return limits;
            }
            _accountMgr.checkAccess(caller, domain);
            if (accountId != null) {
                // Verify account information and permissions
                Account account = _accountDao.findById(accountId);
                if (account == null) {
                    // return empty set
                    return limits;
                }
                _accountMgr.checkAccess(caller, null, true, account);
                domainId = null;
            }
        }
    }
    // Map resource type
    ResourceType resourceType = null;
    if (type != null) {
        try {
            resourceType = ResourceType.values()[type];
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new InvalidParameterValueException("Please specify a valid resource type.");
        }
    }
    // If id is passed in, get the record and return it if permission check has passed
    if (id != null) {
        ResourceLimitVO vo = _resourceLimitDao.findById(id);
        if (vo.getAccountId() != null) {
            _accountMgr.checkAccess(caller, null, true, _accountDao.findById(vo.getAccountId()));
            limits.add(vo);
        } else if (vo.getDomainId() != null) {
            _accountMgr.checkAccess(caller, _domainDao.findById(vo.getDomainId()));
            limits.add(vo);
        }
        return limits;
    }
    // If account is not specified, default it to caller account
    if (accountId == null) {
        if (domainId == null) {
            accountId = caller.getId();
            isAccount = true;
        } else {
            isAccount = false;
        }
    } else {
        isAccount = true;
    }
    SearchBuilder<ResourceLimitVO> sb = _resourceLimitDao.createSearchBuilder();
    sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
    sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ);
    sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ);
    SearchCriteria<ResourceLimitVO> sc = sb.create();
    Filter filter = new Filter(ResourceLimitVO.class, "id", true, startIndex, pageSizeVal);
    if (accountId != null) {
        sc.setParameters("accountId", accountId);
    }
    if (domainId != null) {
        sc.setParameters("domainId", domainId);
        sc.setParameters("accountId", (Object[]) null);
    }
    if (resourceType != null) {
        sc.setParameters("type", resourceType);
    }
    List<ResourceLimitVO> foundLimits = _resourceLimitDao.search(sc, filter);
    if (resourceType != null) {
        if (foundLimits.isEmpty()) {
            if (isAccount) {
                limits.add(new ResourceLimitVO(resourceType, findCorrectResourceLimitForAccount(_accountMgr.getAccount(accountId), resourceType), accountId, ResourceOwnerType.Account));
            } else {
                limits.add(new ResourceLimitVO(resourceType, findCorrectResourceLimitForDomain(_domainDao.findById(domainId), resourceType), domainId, ResourceOwnerType.Domain));
            }
        } else {
            limits.addAll(foundLimits);
        }
    } else {
        limits.addAll(foundLimits);
        // see if any limits are missing from the table, and if yes - get it from the config table and add
        ResourceType[] resourceTypes = ResourceCount.ResourceType.values();
        if (foundLimits.size() != resourceTypes.length) {
            List<String> accountLimitStr = new ArrayList<String>();
            List<String> domainLimitStr = new ArrayList<String>();
            for (ResourceLimitVO foundLimit : foundLimits) {
                if (foundLimit.getAccountId() != null) {
                    accountLimitStr.add(foundLimit.getType().toString());
                } else {
                    domainLimitStr.add(foundLimit.getType().toString());
                }
            }
            // get default from config values
            if (isAccount) {
                if (accountLimitStr.size() < resourceTypes.length) {
                    for (ResourceType rt : resourceTypes) {
                        if (!accountLimitStr.contains(rt.toString()) && rt.supportsOwner(ResourceOwnerType.Account)) {
                            limits.add(new ResourceLimitVO(rt, findCorrectResourceLimitForAccount(_accountMgr.getAccount(accountId), rt), accountId, ResourceOwnerType.Account));
                        }
                    }
                }
            } else {
                if (domainLimitStr.size() < resourceTypes.length) {
                    for (ResourceType rt : resourceTypes) {
                        if (!domainLimitStr.contains(rt.toString()) && rt.supportsOwner(ResourceOwnerType.Domain)) {
                            limits.add(new ResourceLimitVO(rt, findCorrectResourceLimitForDomain(_domainDao.findById(domainId), rt), domainId, ResourceOwnerType.Domain));
                        }
                    }
                }
            }
        }
    }
    return limits;
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) ResourceType(com.cloud.configuration.Resource.ResourceType) ResourceLimitVO(com.cloud.configuration.ResourceLimitVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Filter(com.cloud.utils.db.Filter) Domain(com.cloud.domain.Domain)

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