Search in sources :

Example 66 with Filter

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

the class ManagementServerImpl method searchForClusters.

@Override
public Pair<List<? extends Cluster>, Integer> searchForClusters(final ListClustersCmd cmd) {
    final Object id = cmd.getId();
    final Object name = cmd.getClusterName();
    final Object podId = cmd.getPodId();
    Long zoneId = cmd.getZoneId();
    final Object hypervisorType = cmd.getHypervisorType();
    final Object clusterType = cmd.getClusterType();
    final Object allocationState = cmd.getAllocationState();
    final String keyword = cmd.getKeyword();
    zoneId = _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), zoneId);
    final Filter searchFilter = new Filter(ClusterVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    final SearchBuilder<ClusterVO> sb = _clusterDao.createSearchBuilder();
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE);
    sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ);
    sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ);
    sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ);
    sb.and("clusterType", sb.entity().getClusterType(), SearchCriteria.Op.EQ);
    sb.and("allocationState", sb.entity().getAllocationState(), SearchCriteria.Op.EQ);
    final SearchCriteria<ClusterVO> sc = sb.create();
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (name != null) {
        sc.setParameters("name", "%" + name + "%");
    }
    if (podId != null) {
        sc.setParameters("podId", podId);
    }
    if (zoneId != null) {
        sc.setParameters("dataCenterId", zoneId);
    }
    if (hypervisorType != null) {
        sc.setParameters("hypervisorType", hypervisorType);
    }
    if (clusterType != null) {
        sc.setParameters("clusterType", clusterType);
    }
    if (allocationState != null) {
        sc.setParameters("allocationState", allocationState);
    }
    if (keyword != null) {
        final SearchCriteria<ClusterVO> ssc = _clusterDao.createSearchCriteria();
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("hypervisorType", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    final Pair<List<ClusterVO>, Integer> result = _clusterDao.searchAndCount(sc, searchFilter);
    return new Pair<List<? extends Cluster>, Integer>(result.first(), result.second());
}
Also used : ClusterVO(com.cloud.dc.ClusterVO) Filter(com.cloud.utils.db.Filter) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) Pair(com.cloud.utils.Pair) SSHKeyPair(com.cloud.user.SSHKeyPair)

Example 67 with Filter

use of com.cloud.utils.db.Filter in project CloudStack-archive by CloudStack-extras.

the class UsageManagerImpl method parse.

public void parse(UsageJobVO job, long startDateMillis, long endDateMillis) {
    // TODO: Shouldn't we also allow parsing by the type of usage?
    boolean success = false;
    long timeStart = System.currentTimeMillis();
    long deleteOldStatsTimeMillis = 0L;
    try {
        if ((endDateMillis == 0) || (endDateMillis > timeStart)) {
            endDateMillis = timeStart;
        }
        long lastSuccess = m_usageJobDao.getLastJobSuccessDateMillis();
        if (lastSuccess != 0) {
            // 1 millisecond after
            startDateMillis = lastSuccess + 1;
        }
        if (startDateMillis >= endDateMillis) {
            if (s_logger.isInfoEnabled()) {
                s_logger.info("not parsing usage records since start time mills (" + startDateMillis + ") is on or after end time millis (" + endDateMillis + ")");
            }
            Transaction jobUpdateTxn = Transaction.open(Transaction.USAGE_DB);
            try {
                jobUpdateTxn.start();
                // everything seemed to work...set endDate as the last success date
                m_usageJobDao.updateJobSuccess(job.getId(), startDateMillis, endDateMillis, System.currentTimeMillis() - timeStart, success);
                // create a new job if this is a recurring job
                if (job.getJobType() == UsageJobVO.JOB_TYPE_RECURRING) {
                    m_usageJobDao.createNewJob(m_hostname, m_pid, UsageJobVO.JOB_TYPE_RECURRING);
                }
                jobUpdateTxn.commit();
            } finally {
                jobUpdateTxn.close();
            }
            return;
        }
        deleteOldStatsTimeMillis = startDateMillis;
        Date startDate = new Date(startDateMillis);
        Date endDate = new Date(endDateMillis);
        if (s_logger.isInfoEnabled()) {
            s_logger.info("Parsing usage records between " + startDate + " and " + endDate);
        }
        List<AccountVO> accounts = null;
        List<UserStatisticsVO> userStats = null;
        Map<String, UsageNetworkVO> networkStats = null;
        Transaction userTxn = Transaction.open(Transaction.CLOUD_DB);
        try {
            Long limit = Long.valueOf(500);
            Long offset = Long.valueOf(0);
            Long lastAccountId = m_usageDao.getLastAccountId();
            if (lastAccountId == null) {
                lastAccountId = Long.valueOf(0);
            }
            do {
                Filter filter = new Filter(AccountVO.class, "id", true, offset, limit);
                accounts = m_accountDao.findActiveAccounts(lastAccountId, filter);
                if ((accounts != null) && !accounts.isEmpty()) {
                    // now update the accounts in the cloud_usage db
                    m_usageDao.updateAccounts(accounts);
                }
                offset = new Long(offset.longValue() + limit.longValue());
            } while ((accounts != null) && !accounts.isEmpty());
            // reset offset
            offset = Long.valueOf(0);
            do {
                Filter filter = new Filter(AccountVO.class, "id", true, offset, limit);
                accounts = m_accountDao.findRecentlyDeletedAccounts(lastAccountId, startDate, filter);
                if ((accounts != null) && !accounts.isEmpty()) {
                    // now update the accounts in the cloud_usage db
                    m_usageDao.updateAccounts(accounts);
                }
                offset = new Long(offset.longValue() + limit.longValue());
            } while ((accounts != null) && !accounts.isEmpty());
            // reset offset
            offset = Long.valueOf(0);
            do {
                Filter filter = new Filter(AccountVO.class, "id", true, offset, limit);
                accounts = m_accountDao.findNewAccounts(lastAccountId, filter);
                if ((accounts != null) && !accounts.isEmpty()) {
                    // now copy the accounts to cloud_usage db
                    m_usageDao.saveAccounts(accounts);
                }
                offset = new Long(offset.longValue() + limit.longValue());
            } while ((accounts != null) && !accounts.isEmpty());
            // reset offset
            offset = Long.valueOf(0);
            // get all the user stats to create usage records for the network usage
            Long lastUserStatsId = m_usageDao.getLastUserStatsId();
            if (lastUserStatsId == null) {
                lastUserStatsId = Long.valueOf(0);
            }
            SearchCriteria<UserStatisticsVO> sc2 = m_userStatsDao.createSearchCriteria();
            sc2.addAnd("id", SearchCriteria.Op.LTEQ, lastUserStatsId);
            do {
                Filter filter = new Filter(UserStatisticsVO.class, "id", true, offset, limit);
                userStats = m_userStatsDao.search(sc2, filter);
                if ((userStats != null) && !userStats.isEmpty()) {
                    // now copy the accounts to cloud_usage db
                    m_usageDao.updateUserStats(userStats);
                }
                offset = new Long(offset.longValue() + limit.longValue());
            } while ((userStats != null) && !userStats.isEmpty());
            // reset offset
            offset = Long.valueOf(0);
            sc2 = m_userStatsDao.createSearchCriteria();
            sc2.addAnd("id", SearchCriteria.Op.GT, lastUserStatsId);
            do {
                Filter filter = new Filter(UserStatisticsVO.class, "id", true, offset, limit);
                userStats = m_userStatsDao.search(sc2, filter);
                if ((userStats != null) && !userStats.isEmpty()) {
                    // now copy the accounts to cloud_usage db
                    m_usageDao.saveUserStats(userStats);
                }
                offset = new Long(offset.longValue() + limit.longValue());
            } while ((userStats != null) && !userStats.isEmpty());
        } finally {
            userTxn.close();
        }
        // TODO:  Fetch a maximum number of events and process them before moving on to the next range of events
        // - get a list of the latest events
        // - insert the latest events into the usage.events table
        List<UsageEventVO> events = _usageEventDao.getRecentEvents(new Date(endDateMillis));
        Transaction usageTxn = Transaction.open(Transaction.USAGE_DB);
        try {
            usageTxn.start();
            // to newest, so just test against the first event)
            if ((events != null) && (events.size() > 0)) {
                Date oldestEventDate = events.get(0).getCreateDate();
                if (oldestEventDate.getTime() < startDateMillis) {
                    startDateMillis = oldestEventDate.getTime();
                    startDate = new Date(startDateMillis);
                }
                // - create the usage records using the parse methods below
                for (UsageEventVO event : events) {
                    event.setProcessed(true);
                    _usageEventDao.update(event.getId(), event);
                    createHelperRecord(event);
                }
            }
            // TODO:  Fetch a maximum number of user stats and process them before moving on to the next range of user stats
            // get user stats in order to compute network usage
            networkStats = m_usageNetworkDao.getRecentNetworkStats();
            Calendar recentlyDeletedCal = Calendar.getInstance(m_usageTimezone);
            recentlyDeletedCal.setTimeInMillis(startDateMillis);
            recentlyDeletedCal.add(Calendar.MINUTE, -1 * THREE_DAYS_IN_MINUTES);
            Date recentlyDeletedDate = recentlyDeletedCal.getTime();
            // Keep track of user stats for an account, across all of its public IPs
            Map<String, UserStatisticsVO> aggregatedStats = new HashMap<String, UserStatisticsVO>();
            int startIndex = 0;
            do {
                userStats = m_userStatsDao.listActiveAndRecentlyDeleted(recentlyDeletedDate, startIndex, 500);
                if (userStats != null) {
                    for (UserStatisticsVO userStat : userStats) {
                        if (userStat.getDeviceId() != null) {
                            String hostKey = userStat.getDataCenterId() + "-" + userStat.getAccountId() + "-Host-" + userStat.getDeviceId();
                            UserStatisticsVO hostAggregatedStat = aggregatedStats.get(hostKey);
                            if (hostAggregatedStat == null) {
                                hostAggregatedStat = new UserStatisticsVO(userStat.getAccountId(), userStat.getDataCenterId(), userStat.getPublicIpAddress(), userStat.getDeviceId(), userStat.getDeviceType(), userStat.getNetworkId());
                            }
                            hostAggregatedStat.setAggBytesSent(hostAggregatedStat.getAggBytesSent() + userStat.getAggBytesSent());
                            hostAggregatedStat.setAggBytesReceived(hostAggregatedStat.getAggBytesReceived() + userStat.getAggBytesReceived());
                            aggregatedStats.put(hostKey, hostAggregatedStat);
                        }
                    }
                }
                startIndex += 500;
            } while ((userStats != null) && !userStats.isEmpty());
            // loop over the user stats, create delta entries in the usage_network helper table
            int numAcctsProcessed = 0;
            for (String key : aggregatedStats.keySet()) {
                UsageNetworkVO currentNetworkStats = null;
                if (networkStats != null) {
                    currentNetworkStats = networkStats.get(key);
                }
                createNetworkHelperEntry(aggregatedStats.get(key), currentNetworkStats, endDateMillis);
                numAcctsProcessed++;
            }
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("created network stats helper entries for " + numAcctsProcessed + " accts");
            }
            // commit the helper records, then start a new transaction
            usageTxn.commit();
            usageTxn.start();
            boolean parsed = false;
            numAcctsProcessed = 0;
            Date currentStartDate = startDate;
            Date currentEndDate = endDate;
            Date tempDate = endDate;
            Calendar aggregateCal = Calendar.getInstance(m_usageTimezone);
            while ((tempDate.after(startDate)) && ((tempDate.getTime() - startDate.getTime()) > 60000)) {
                currentEndDate = tempDate;
                aggregateCal.setTime(tempDate);
                aggregateCal.add(Calendar.MINUTE, -m_aggregationDuration);
                tempDate = aggregateCal.getTime();
            }
            while (!currentEndDate.after(endDate) || (currentEndDate.getTime() - endDate.getTime() < 60000)) {
                Long offset = Long.valueOf(0);
                Long limit = Long.valueOf(500);
                do {
                    Filter filter = new Filter(AccountVO.class, "id", true, offset, limit);
                    accounts = m_accountDao.listAll(filter);
                    if ((accounts != null) && !accounts.isEmpty()) {
                        for (AccountVO account : accounts) {
                            parsed = parseHelperTables(account, currentStartDate, currentEndDate);
                            numAcctsProcessed++;
                        }
                    }
                    offset = new Long(offset.longValue() + limit.longValue());
                } while ((accounts != null) && !accounts.isEmpty());
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("processed VM/Network Usage for " + numAcctsProcessed + " ACTIVE accts");
                }
                numAcctsProcessed = 0;
                // reset offset
                offset = Long.valueOf(0);
                do {
                    Filter filter = new Filter(AccountVO.class, "id", true, offset, limit);
                    accounts = m_accountDao.findRecentlyDeletedAccounts(null, recentlyDeletedDate, filter);
                    if ((accounts != null) && !accounts.isEmpty()) {
                        for (AccountVO account : accounts) {
                            parsed = parseHelperTables(account, currentStartDate, currentEndDate);
                            List<Long> publicTemplates = m_usageDao.listPublicTemplatesByAccount(account.getId());
                            for (Long templateId : publicTemplates) {
                                //mark public templates owned by deleted accounts as deleted
                                List<UsageStorageVO> storageVOs = m_usageStorageDao.listById(account.getId(), templateId, StorageTypes.TEMPLATE);
                                if (storageVOs.size() > 1) {
                                    s_logger.warn("More that one usage entry for storage: " + templateId + " assigned to account: " + account.getId() + "; marking them all as deleted...");
                                }
                                for (UsageStorageVO storageVO : storageVOs) {
                                    if (s_logger.isDebugEnabled()) {
                                        s_logger.debug("deleting template: " + storageVO.getId() + " from account: " + storageVO.getAccountId());
                                    }
                                    storageVO.setDeleted(account.getRemoved());
                                    m_usageStorageDao.update(storageVO);
                                }
                            }
                            numAcctsProcessed++;
                        }
                    }
                    offset = new Long(offset.longValue() + limit.longValue());
                } while ((accounts != null) && !accounts.isEmpty());
                currentStartDate = new Date(currentEndDate.getTime() + 1);
                aggregateCal.setTime(currentEndDate);
                aggregateCal.add(Calendar.MINUTE, m_aggregationDuration);
                currentEndDate = aggregateCal.getTime();
            }
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("processed Usage for " + numAcctsProcessed + " RECENTLY DELETED accts");
            }
            //        do we want to break out of processing accounts and rollback if there are errors?
            if (!parsed) {
                usageTxn.rollback();
            } else {
                success = true;
            }
        } catch (Exception ex) {
            s_logger.error("Exception in usage manager", ex);
            usageTxn.rollback();
        } finally {
            // everything seemed to work...set endDate as the last success date
            m_usageJobDao.updateJobSuccess(job.getId(), startDateMillis, endDateMillis, System.currentTimeMillis() - timeStart, success);
            // create a new job if this is a recurring job
            if (job.getJobType() == UsageJobVO.JOB_TYPE_RECURRING) {
                m_usageJobDao.createNewJob(m_hostname, m_pid, UsageJobVO.JOB_TYPE_RECURRING);
            }
            usageTxn.commit();
            usageTxn.close();
            // switch back to CLOUD_DB
            Transaction swap = Transaction.open(Transaction.CLOUD_DB);
            if (!success) {
                _alertMgr.sendAlert(AlertManager.ALERT_TYPE_USAGE_SERVER_RESULT, 0, new Long(0), "Usage job failed. Job id: " + job.getId(), "Usage job failed. Job id: " + job.getId());
            } else {
                _alertMgr.clearAlert(AlertManager.ALERT_TYPE_USAGE_SERVER_RESULT, 0, 0);
            }
            swap.close();
        }
    } catch (Exception e) {
        s_logger.error("Usage Manager error", e);
    }
}
Also used : HashMap(java.util.HashMap) Calendar(java.util.Calendar) UsageEventVO(com.cloud.event.UsageEventVO) AccountVO(com.cloud.user.AccountVO) Date(java.util.Date) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) SQLException(java.sql.SQLException) Transaction(com.cloud.utils.db.Transaction) Filter(com.cloud.utils.db.Filter) UserStatisticsVO(com.cloud.user.UserStatisticsVO)

Example 68 with Filter

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

the class QueryManagerImpl method listProjectsInternal.

private Pair<List<ProjectJoinVO>, Integer> listProjectsInternal(ListProjectsCmd cmd) {
    Long id = cmd.getId();
    String name = cmd.getName();
    String displayText = cmd.getDisplayText();
    String state = cmd.getState();
    String accountName = cmd.getAccountName();
    Long domainId = cmd.getDomainId();
    String keyword = cmd.getKeyword();
    Long startIndex = cmd.getStartIndex();
    Long pageSize = cmd.getPageSizeVal();
    boolean listAll = cmd.listAll();
    boolean isRecursive = cmd.isRecursive();
    cmd.getTags();
    Account caller = CallContext.current().getCallingAccount();
    Long accountId = null;
    String path = null;
    Filter searchFilter = new Filter(ProjectJoinVO.class, "id", false, startIndex, pageSize);
    SearchBuilder<ProjectJoinVO> sb = _projectJoinDao.createSearchBuilder();
    // select distinct
    sb.select(null, Func.DISTINCT, sb.entity().getId());
    if (_accountMgr.isAdmin(caller.getId())) {
        if (domainId != null) {
            DomainVO domain = _domainDao.findById(domainId);
            if (domain == null) {
                throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist in the system");
            }
            _accountMgr.checkAccess(caller, domain);
            if (accountName != null) {
                Account owner = _accountMgr.getActiveAccountByName(accountName, domainId);
                if (owner == null) {
                    throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId);
                }
                accountId = owner.getId();
            }
        } else {
            // domainId == null
            if (accountName != null) {
                throw new InvalidParameterValueException("could not find account " + accountName + " because domain is not specified");
            }
        }
    } else {
        if (accountName != null && !accountName.equals(caller.getAccountName())) {
            throw new PermissionDeniedException("Can't list account " + accountName + " projects; unauthorized");
        }
        if (domainId != null && !domainId.equals(caller.getDomainId())) {
            throw new PermissionDeniedException("Can't list domain id= " + domainId + " projects; unauthorized");
        }
        accountId = caller.getId();
    }
    if (domainId == null && accountId == null && (_accountMgr.isNormalUser(caller.getId()) || !listAll)) {
        accountId = caller.getId();
    } else if (_accountMgr.isDomainAdmin(caller.getId()) || (isRecursive && !listAll)) {
        DomainVO domain = _domainDao.findById(caller.getDomainId());
        path = domain.getPath();
    }
    if (path != null) {
        sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE);
    }
    if (accountId != null) {
        sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ);
    }
    SearchCriteria<ProjectJoinVO> sc = sb.create();
    if (id != null) {
        sc.addAnd("id", Op.EQ, id);
    }
    if (domainId != null && !isRecursive) {
        sc.addAnd("domainId", Op.EQ, domainId);
    }
    if (name != null) {
        sc.addAnd("name", Op.EQ, name);
    }
    if (displayText != null) {
        sc.addAnd("displayText", Op.EQ, displayText);
    }
    if (accountId != null) {
        sc.setParameters("accountId", accountId);
    }
    if (state != null) {
        sc.addAnd("state", Op.EQ, state);
    }
    if (keyword != null) {
        SearchCriteria<ProjectJoinVO> ssc = _projectJoinDao.createSearchCriteria();
        ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("name", SearchCriteria.Op.SC, ssc);
    }
    if (path != null) {
        sc.setParameters("domainPath", path);
    }
    // search distinct projects to get count
    Pair<List<ProjectJoinVO>, Integer> uniquePrjPair = _projectJoinDao.searchAndCount(sc, searchFilter);
    Integer count = uniquePrjPair.second();
    if (count.intValue() == 0) {
        // handle empty result cases
        return uniquePrjPair;
    }
    List<ProjectJoinVO> uniquePrjs = uniquePrjPair.first();
    Long[] prjIds = new Long[uniquePrjs.size()];
    int i = 0;
    for (ProjectJoinVO v : uniquePrjs) {
        prjIds[i++] = v.getId();
    }
    List<ProjectJoinVO> prjs = _projectJoinDao.searchByIds(prjIds);
    return new Pair<List<ProjectJoinVO>, Integer>(prjs, count);
}
Also used : Account(com.cloud.user.Account) ProjectJoinVO(com.cloud.api.query.vo.ProjectJoinVO) 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) ArrayList(java.util.ArrayList) List(java.util.List) Pair(com.cloud.utils.Pair)

Example 69 with Filter

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

the class QueryManagerImpl method searchForEventsInternal.

private Pair<List<EventJoinVO>, Integer> searchForEventsInternal(ListEventsCmd cmd) {
    Account caller = CallContext.current().getCallingAccount();
    List<Long> permittedAccounts = new ArrayList<Long>();
    Long id = cmd.getId();
    String type = cmd.getType();
    String level = cmd.getLevel();
    Date startDate = cmd.getStartDate();
    Date endDate = cmd.getEndDate();
    String keyword = cmd.getKeyword();
    Integer entryTime = cmd.getEntryTime();
    Integer duration = cmd.getDuration();
    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 searchFilter = new Filter(EventJoinVO.class, "createDate", false, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchBuilder<EventJoinVO> sb = _eventJoinDao.createSearchBuilder();
    _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ);
    sb.and("levelL", sb.entity().getLevel(), SearchCriteria.Op.LIKE);
    sb.and("levelEQ", sb.entity().getLevel(), SearchCriteria.Op.EQ);
    sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ);
    sb.and("createDateB", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN);
    sb.and("createDateG", sb.entity().getCreateDate(), SearchCriteria.Op.GTEQ);
    sb.and("createDateL", sb.entity().getCreateDate(), SearchCriteria.Op.LTEQ);
    sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ);
    sb.and("startId", sb.entity().getStartId(), SearchCriteria.Op.EQ);
    sb.and("createDate", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN);
    sb.and("displayEvent", sb.entity().getDisplay(), SearchCriteria.Op.EQ);
    sb.and("archived", sb.entity().getArchived(), SearchCriteria.Op.EQ);
    SearchCriteria<EventJoinVO> sc = sb.create();
    // building ACL condition
    _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    // For end users display only enabled events
    if (!_accountMgr.isRootAdmin(caller.getId())) {
        sc.setParameters("displayEvent", true);
    }
    if (id != null) {
        sc.setParameters("id", id);
    }
    if (keyword != null) {
        SearchCriteria<EventJoinVO> ssc = _eventJoinDao.createSearchCriteria();
        ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        ssc.addOr("level", SearchCriteria.Op.LIKE, "%" + keyword + "%");
        sc.addAnd("level", SearchCriteria.Op.SC, ssc);
    }
    if (level != null) {
        sc.setParameters("levelEQ", level);
    }
    if (type != null) {
        sc.setParameters("type", type);
    }
    if (startDate != null && endDate != null) {
        sc.setParameters("createDateB", startDate, endDate);
    } else if (startDate != null) {
        sc.setParameters("createDateG", startDate);
    } else if (endDate != null) {
        sc.setParameters("createDateL", endDate);
    }
    sc.setParameters("archived", false);
    Pair<List<EventJoinVO>, Integer> eventPair = null;
    // searchAndCount should be good enough.
    if ((entryTime != null) && (duration != null)) {
    // TODO: waiting for response from dev list, logic is mystery to
    // me!!
    /*
             * if (entryTime <= duration) { throw new
             * InvalidParameterValueException
             * ("Entry time must be greater than duration"); } Calendar calMin =
             * Calendar.getInstance(); Calendar calMax = Calendar.getInstance();
             * calMin.add(Calendar.SECOND, -entryTime);
             * calMax.add(Calendar.SECOND, -duration); Date minTime =
             * calMin.getTime(); Date maxTime = calMax.getTime();
             *
             * sc.setParameters("state", com.cloud.event.Event.State.Completed);
             * sc.setParameters("startId", 0); sc.setParameters("createDate",
             * minTime, maxTime); List<EventJoinVO> startedEvents =
             * _eventJoinDao.searchAllEvents(sc, searchFilter);
             * List<EventJoinVO> pendingEvents = new ArrayList<EventJoinVO>();
             * for (EventVO event : startedEvents) { EventVO completedEvent =
             * _eventDao.findCompletedEvent(event.getId()); if (completedEvent
             * == null) { pendingEvents.add(event); } } return pendingEvents;
             */
    } else {
        eventPair = _eventJoinDao.searchAndCount(sc, searchFilter);
    }
    return eventPair;
}
Also used : Account(com.cloud.user.Account) Ternary(com.cloud.utils.Ternary) ArrayList(java.util.ArrayList) Date(java.util.Date) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) ArrayList(java.util.ArrayList) List(java.util.List) EventJoinVO(com.cloud.api.query.vo.EventJoinVO)

Example 70 with Filter

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

the class QueryManagerImpl method searchForDomainsInternal.

private Pair<List<DomainJoinVO>, Integer> searchForDomainsInternal(ListDomainsCmd cmd) {
    Account caller = CallContext.current().getCallingAccount();
    Long domainId = cmd.getId();
    boolean listAll = cmd.listAll();
    boolean isRecursive = false;
    if (domainId != null) {
        Domain domain = _domainDao.findById(domainId);
        if (domain == null) {
            throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist");
        }
        _accountMgr.checkAccess(caller, domain);
    } else {
        if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) {
            domainId = caller.getDomainId();
        }
        if (listAll) {
            isRecursive = true;
        }
    }
    Filter searchFilter = new Filter(DomainJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal());
    String domainName = cmd.getDomainName();
    Integer level = cmd.getLevel();
    Object keyword = cmd.getKeyword();
    SearchBuilder<DomainJoinVO> sb = _domainJoinDao.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);
    SearchCriteria<DomainJoinVO> sc = sb.create();
    if (keyword != null) {
        SearchCriteria<DomainJoinVO> ssc = _domainJoinDao.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", _domainDao.findById(domainId).getPath() + "%");
        } else {
            sc.setParameters("id", domainId);
        }
    }
    // return only Active domains to the API
    sc.setParameters("state", Domain.State.Active);
    return _domainJoinDao.searchAndCount(sc, searchFilter);
}
Also used : Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) Domain(com.cloud.domain.Domain) DomainJoinVO(com.cloud.api.query.vo.DomainJoinVO)

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