Search in sources :

Example 11 with SearchCriteria

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

the class QueryManagerImpl method listDataCentersInternal.

private Pair<List<DataCenterJoinVO>, Integer> listDataCentersInternal(ListZonesCmd cmd) {
    Account account = CallContext.current().getCallingAccount();
    Long domainId = cmd.getDomainId();
    Long id = cmd.getId();
    String keyword = cmd.getKeyword();
    String name = cmd.getName();
    String networkType = cmd.getNetworkType();
    Map<String, String> resourceTags = cmd.getTags();
    SearchBuilder<DataCenterJoinVO> sb = _dcJoinDao.createSearchBuilder();
    if (resourceTags != null && !resourceTags.isEmpty()) {
        SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
        for (int count = 0; count < resourceTags.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);
    }
    Filter searchFilter = new Filter(DataCenterJoinVO.class, null, false, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchCriteria<DataCenterJoinVO> sc = sb.create();
    if (networkType != null) {
        sc.addAnd("networkType", SearchCriteria.Op.EQ, networkType);
    }
    if (id != null) {
        sc.addAnd("id", SearchCriteria.Op.EQ, id);
    } else if (name != null) {
        sc.addAnd("name", SearchCriteria.Op.EQ, name);
    } else {
        if (keyword != null) {
            SearchCriteria<DataCenterJoinVO> ssc = _dcJoinDao.createSearchCriteria();
            ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
            ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%");
            sc.addAnd("name", SearchCriteria.Op.SC, ssc);
        }
        /*
             * List all resources due to Explicit Dedication except the
             * dedicated resources of other account
             */
        if (domainId != null) {
            //
            // for domainId != null // right now, we made the decision to
            // only list zones associated // with this domain, private zone
            sc.addAnd("domainId", SearchCriteria.Op.EQ, domainId);
            if (_accountMgr.isNormalUser(account.getId())) {
                // accountId == null (zones dedicated to a domain) or
                // accountId = caller
                SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
                sdc.addOr("accountId", SearchCriteria.Op.EQ, account.getId());
                sdc.addOr("accountId", SearchCriteria.Op.NULL);
                sc.addAnd("accountId", SearchCriteria.Op.SC, sdc);
            }
        } else if (_accountMgr.isNormalUser(account.getId())) {
            // it was decided to return all zones for the user's domain, and
            // everything above till root
            // list all zones belonging to this domain, and all of its
            // parents
            // check the parent, if not null, add zones for that parent to
            // list
            // find all domain Id up to root domain for this account
            List<Long> 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());
            }
            // domainId == null (public zones) or domainId IN [all domain id
            // up to root domain]
            SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
            sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
            sdc.addOr("domainId", SearchCriteria.Op.NULL);
            sc.addAnd("domainId", SearchCriteria.Op.SC, sdc);
            // remove disabled zones
            sc.addAnd("allocationState", SearchCriteria.Op.NEQ, Grouping.AllocationState.Disabled);
            // accountId == null (zones dedicated to a domain) or
            // accountId = caller
            SearchCriteria<DataCenterJoinVO> sdc2 = _dcJoinDao.createSearchCriteria();
            sdc2.addOr("accountId", SearchCriteria.Op.EQ, account.getId());
            sdc2.addOr("accountId", SearchCriteria.Op.NULL);
            sc.addAnd("accountId", SearchCriteria.Op.SC, sdc2);
            // remove Dedicated zones not dedicated to this domainId or
            // subdomainId
            List<Long> dedicatedZoneIds = removeDedicatedZoneNotSuitabe(domainIds);
            if (!dedicatedZoneIds.isEmpty()) {
                sdc.addAnd("id", SearchCriteria.Op.NIN, dedicatedZoneIds.toArray(new Object[dedicatedZoneIds.size()]));
            }
        } else if (_accountMgr.isDomainAdmin(account.getId()) || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) {
            // it was decided to return all zones for the domain admin, and
            // everything above till root, as well as zones till the domain
            // leaf
            List<Long> 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());
            // find all domain Ids till leaf
            List<DomainVO> allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(), domainRecord.getId());
            for (DomainVO domain : allChildDomains) {
                domainIds.add(domain.getId());
            }
            // then find all domain Id up to root domain for this account
            while (domainRecord.getParent() != null) {
                domainRecord = _domainDao.findById(domainRecord.getParent());
                domainIds.add(domainRecord.getId());
            }
            // domainId == null (public zones) or domainId IN [all domain id
            // up to root domain]
            SearchCriteria<DataCenterJoinVO> sdc = _dcJoinDao.createSearchCriteria();
            sdc.addOr("domainId", SearchCriteria.Op.IN, domainIds.toArray());
            sdc.addOr("domainId", SearchCriteria.Op.NULL);
            sc.addAnd("domainId", SearchCriteria.Op.SC, sdc);
            // remove disabled zones
            sc.addAnd("allocationState", SearchCriteria.Op.NEQ, Grouping.AllocationState.Disabled);
            // remove Dedicated zones not dedicated to this domainId or
            // subdomainId
            List<Long> dedicatedZoneIds = removeDedicatedZoneNotSuitabe(domainIds);
            if (!dedicatedZoneIds.isEmpty()) {
                sdc.addAnd("id", SearchCriteria.Op.NIN, dedicatedZoneIds.toArray(new Object[dedicatedZoneIds.size()]));
            }
        }
        // handle available=FALSE option, only return zones with at least
        // one VM running there
        Boolean available = cmd.isAvailable();
        if (account != null) {
            if ((available != null) && Boolean.FALSE.equals(available)) {
                // data centers with
                Set<Long> dcIds = new HashSet<Long>();
                // at least one VM
                // running
                List<DomainRouterVO> routers = _routerDao.listBy(account.getId());
                for (DomainRouterVO router : routers) {
                    dcIds.add(router.getDataCenterId());
                }
                if (dcIds.size() == 0) {
                    return new Pair<List<DataCenterJoinVO>, Integer>(new ArrayList<DataCenterJoinVO>(), 0);
                } else {
                    sc.addAnd("id", SearchCriteria.Op.IN, dcIds.toArray());
                }
            }
        }
    }
    if (resourceTags != null && !resourceTags.isEmpty()) {
        int count = 0;
        sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.Zone.toString());
        for (Map.Entry<String, String> entry : resourceTags.entrySet()) {
            sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), entry.getKey());
            sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), entry.getValue());
            count++;
        }
    }
    return _dcJoinDao.searchAndCount(sc, searchFilter);
}
Also used : DataCenterJoinVO(com.cloud.api.query.vo.DataCenterJoinVO) Account(com.cloud.user.Account) HashSet(java.util.HashSet) Set(java.util.Set) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) ArrayList(java.util.ArrayList) ResourceTagVO(com.cloud.tags.ResourceTagVO) ArrayList(java.util.ArrayList) List(java.util.List) SearchCriteria(com.cloud.utils.db.SearchCriteria) DomainVO(com.cloud.domain.DomainVO) TemplateFilter(com.cloud.template.VirtualMachineTemplate.TemplateFilter) Filter(com.cloud.utils.db.Filter) Map(java.util.Map) DomainRouterVO(com.cloud.vm.DomainRouterVO)

Example 12 with SearchCriteria

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

the class UserVmManagerImpl method collectVmDiskStatistics.

@Override
public void collectVmDiskStatistics(final UserVmVO userVm) {
    // support KVM only util 2013.06.25
    if (!userVm.getHypervisorType().equals(HypervisorType.KVM))
        return;
    s_logger.debug("Collect vm disk statistics from host before stopping Vm");
    long hostId = userVm.getHostId();
    List<String> vmNames = new ArrayList<String>();
    vmNames.add(userVm.getInstanceName());
    final HostVO host = _hostDao.findById(hostId);
    GetVmDiskStatsAnswer diskStatsAnswer = null;
    try {
        diskStatsAnswer = (GetVmDiskStatsAnswer) _agentMgr.easySend(hostId, new GetVmDiskStatsCommand(vmNames, host.getGuid(), host.getName()));
    } catch (Exception e) {
        s_logger.warn("Error while collecting disk stats for vm: " + userVm.getInstanceName() + " from host: " + host.getName(), e);
        return;
    }
    if (diskStatsAnswer != null) {
        if (!diskStatsAnswer.getResult()) {
            s_logger.warn("Error while collecting disk stats vm: " + userVm.getInstanceName() + " from host: " + host.getName() + "; details: " + diskStatsAnswer.getDetails());
            return;
        }
        try {
            final GetVmDiskStatsAnswer diskStatsAnswerFinal = diskStatsAnswer;
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    HashMap<String, List<VmDiskStatsEntry>> vmDiskStatsByName = diskStatsAnswerFinal.getVmDiskStatsMap();
                    if (vmDiskStatsByName == null)
                        return;
                    List<VmDiskStatsEntry> vmDiskStats = vmDiskStatsByName.get(userVm.getInstanceName());
                    if (vmDiskStats == null)
                        return;
                    for (VmDiskStatsEntry vmDiskStat : vmDiskStats) {
                        SearchCriteria<VolumeVO> sc_volume = _volsDao.createSearchCriteria();
                        sc_volume.addAnd("path", SearchCriteria.Op.EQ, vmDiskStat.getPath());
                        List<VolumeVO> volumes = _volsDao.search(sc_volume, null);
                        if ((volumes == null) || (volumes.size() == 0))
                            break;
                        VolumeVO volume = volumes.get(0);
                        VmDiskStatisticsVO previousVmDiskStats = _vmDiskStatsDao.findBy(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
                        VmDiskStatisticsVO vmDiskStat_lock = _vmDiskStatsDao.lock(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
                        if ((vmDiskStat.getIORead() == 0) && (vmDiskStat.getIOWrite() == 0) && (vmDiskStat.getBytesRead() == 0) && (vmDiskStat.getBytesWrite() == 0)) {
                            s_logger.debug("Read/Write of IO and Bytes are both 0. Not updating vm_disk_statistics");
                            continue;
                        }
                        if (vmDiskStat_lock == null) {
                            s_logger.warn("unable to find vm disk stats from host for account: " + userVm.getAccountId() + " with vmId: " + userVm.getId() + " and volumeId:" + volume.getId());
                            continue;
                        }
                        if (previousVmDiskStats != null && ((previousVmDiskStats.getCurrentIORead() != vmDiskStat_lock.getCurrentIORead()) || ((previousVmDiskStats.getCurrentIOWrite() != vmDiskStat_lock.getCurrentIOWrite()) || (previousVmDiskStats.getCurrentBytesRead() != vmDiskStat_lock.getCurrentBytesRead()) || (previousVmDiskStats.getCurrentBytesWrite() != vmDiskStat_lock.getCurrentBytesWrite())))) {
                            s_logger.debug("vm disk stats changed from the time GetVmDiskStatsCommand was sent. " + "Ignoring current answer. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " IO Read: " + vmDiskStat.getIORead() + " IO Write: " + vmDiskStat.getIOWrite() + " Bytes Read: " + vmDiskStat.getBytesRead() + " Bytes Write: " + vmDiskStat.getBytesWrite());
                            continue;
                        }
                        if (vmDiskStat_lock.getCurrentIORead() > vmDiskStat.getIORead()) {
                            if (s_logger.isDebugEnabled()) {
                                s_logger.debug("Read # of IO that's less than the last one.  " + "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getIORead() + " Stored: " + vmDiskStat_lock.getCurrentIORead());
                            }
                            vmDiskStat_lock.setNetIORead(vmDiskStat_lock.getNetIORead() + vmDiskStat_lock.getCurrentIORead());
                        }
                        vmDiskStat_lock.setCurrentIORead(vmDiskStat.getIORead());
                        if (vmDiskStat_lock.getCurrentIOWrite() > vmDiskStat.getIOWrite()) {
                            if (s_logger.isDebugEnabled()) {
                                s_logger.debug("Write # of IO that's less than the last one.  " + "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getIOWrite() + " Stored: " + vmDiskStat_lock.getCurrentIOWrite());
                            }
                            vmDiskStat_lock.setNetIOWrite(vmDiskStat_lock.getNetIOWrite() + vmDiskStat_lock.getCurrentIOWrite());
                        }
                        vmDiskStat_lock.setCurrentIOWrite(vmDiskStat.getIOWrite());
                        if (vmDiskStat_lock.getCurrentBytesRead() > vmDiskStat.getBytesRead()) {
                            if (s_logger.isDebugEnabled()) {
                                s_logger.debug("Read # of Bytes that's less than the last one.  " + "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getBytesRead() + " Stored: " + vmDiskStat_lock.getCurrentBytesRead());
                            }
                            vmDiskStat_lock.setNetBytesRead(vmDiskStat_lock.getNetBytesRead() + vmDiskStat_lock.getCurrentBytesRead());
                        }
                        vmDiskStat_lock.setCurrentBytesRead(vmDiskStat.getBytesRead());
                        if (vmDiskStat_lock.getCurrentBytesWrite() > vmDiskStat.getBytesWrite()) {
                            if (s_logger.isDebugEnabled()) {
                                s_logger.debug("Write # of Bytes that's less than the last one.  " + "Assuming something went wrong and persisting it. Host: " + host.getName() + " . VM: " + vmDiskStat.getVmName() + " Reported: " + vmDiskStat.getBytesWrite() + " Stored: " + vmDiskStat_lock.getCurrentBytesWrite());
                            }
                            vmDiskStat_lock.setNetBytesWrite(vmDiskStat_lock.getNetBytesWrite() + vmDiskStat_lock.getCurrentBytesWrite());
                        }
                        vmDiskStat_lock.setCurrentBytesWrite(vmDiskStat.getBytesWrite());
                        if (!_dailyOrHourly) {
                            //update agg bytes
                            vmDiskStat_lock.setAggIORead(vmDiskStat_lock.getNetIORead() + vmDiskStat_lock.getCurrentIORead());
                            vmDiskStat_lock.setAggIOWrite(vmDiskStat_lock.getNetIOWrite() + vmDiskStat_lock.getCurrentIOWrite());
                            vmDiskStat_lock.setAggBytesRead(vmDiskStat_lock.getNetBytesRead() + vmDiskStat_lock.getCurrentBytesRead());
                            vmDiskStat_lock.setAggBytesWrite(vmDiskStat_lock.getNetBytesWrite() + vmDiskStat_lock.getCurrentBytesWrite());
                        }
                        _vmDiskStatsDao.update(vmDiskStat_lock.getId(), vmDiskStat_lock);
                    }
                }
            });
        } catch (Exception e) {
            s_logger.warn("Unable to update vm disk statistics for vm: " + userVm.getId() + " from host: " + hostId, e);
        }
    }
}
Also used : LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) VmDiskStatisticsVO(com.cloud.user.VmDiskStatisticsVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) VmDiskStatsEntry(com.cloud.agent.api.VmDiskStatsEntry) HostVO(com.cloud.host.HostVO) ExecutionException(com.cloud.utils.exception.ExecutionException) AgentUnavailableException(com.cloud.exception.AgentUnavailableException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) VirtualMachineMigrationException(com.cloud.exception.VirtualMachineMigrationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) CloudException(com.cloud.exception.CloudException) OperationTimedoutException(com.cloud.exception.OperationTimedoutException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) StorageUnavailableException(com.cloud.exception.StorageUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) ConfigurationException(javax.naming.ConfigurationException) ManagementServerException(com.cloud.exception.ManagementServerException) SearchCriteria(com.cloud.utils.db.SearchCriteria) GetVmDiskStatsAnswer(com.cloud.agent.api.GetVmDiskStatsAnswer) GetVmDiskStatsCommand(com.cloud.agent.api.GetVmDiskStatsCommand) VolumeVO(com.cloud.storage.VolumeVO) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List)

Example 13 with SearchCriteria

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

the class DcDetailsDaoImpl method deleteDetails.

@Override
public void deleteDetails(long dcId) {
    SearchCriteria sc = DcSearch.create();
    sc.setParameters("dcId", dcId);
    List<DcDetailVO> results = search(sc, null);
    for (DcDetailVO result : results) {
        remove(result.getId());
    }
}
Also used : DcDetailVO(org.apache.cloudstack.engine.datacenter.entity.api.db.DcDetailVO) SearchCriteria(com.cloud.utils.db.SearchCriteria)

Example 14 with SearchCriteria

use of com.cloud.utils.db.SearchCriteria 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)

Example 15 with SearchCriteria

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

the class UsageManagerImpl method createVolumeHelperEvent.

private void createVolumeHelperEvent(UsageEventVO event) {
    long volId = event.getResourceId();
    if (EventTypes.EVENT_VOLUME_CREATE.equals(event.getType()) || EventTypes.EVENT_VOLUME_RESIZE.equals(event.getType())) {
        SearchCriteria<UsageVolumeVO> sc = _usageVolumeDao.createSearchCriteria();
        sc.addAnd("accountId", SearchCriteria.Op.EQ, event.getAccountId());
        sc.addAnd("id", SearchCriteria.Op.EQ, volId);
        sc.addAnd("deleted", SearchCriteria.Op.NULL);
        List<UsageVolumeVO> volumesVOs = _usageVolumeDao.search(sc, null);
        if (volumesVOs.size() > 0) {
            //This is a safeguard to avoid double counting of volumes.
            s_logger.error("Found duplicate usage entry for volume: " + volId + " assigned to account: " + event.getAccountId() + "; marking as deleted...");
        }
        //an entry exists if it is a resize volume event. marking the existing deleted and creating a new one in the case of resize.
        for (UsageVolumeVO volumesVO : volumesVOs) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("deleting volume: " + volumesVO.getId() + " from account: " + volumesVO.getAccountId());
            }
            volumesVO.setDeleted(event.getCreateDate());
            _usageVolumeDao.update(volumesVO);
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("create volume with id : " + volId + " for account: " + event.getAccountId());
        }
        Account acct = _accountDao.findByIdIncludingRemoved(event.getAccountId());
        UsageVolumeVO volumeVO = new UsageVolumeVO(volId, event.getZoneId(), event.getAccountId(), acct.getDomainId(), event.getOfferingId(), event.getTemplateId(), event.getSize(), event.getCreateDate(), null);
        _usageVolumeDao.persist(volumeVO);
    } else if (EventTypes.EVENT_VOLUME_DELETE.equals(event.getType())) {
        SearchCriteria<UsageVolumeVO> sc = _usageVolumeDao.createSearchCriteria();
        sc.addAnd("accountId", SearchCriteria.Op.EQ, event.getAccountId());
        sc.addAnd("id", SearchCriteria.Op.EQ, volId);
        sc.addAnd("deleted", SearchCriteria.Op.NULL);
        List<UsageVolumeVO> volumesVOs = _usageVolumeDao.search(sc, null);
        if (volumesVOs.size() > 1) {
            s_logger.warn("More that one usage entry for volume: " + volId + " assigned to account: " + event.getAccountId() + "; marking them all as deleted...");
        }
        for (UsageVolumeVO volumesVO : volumesVOs) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("deleting volume: " + volumesVO.getId() + " from account: " + volumesVO.getAccountId());
            }
            // there really shouldn't be more than one
            volumesVO.setDeleted(event.getCreateDate());
            _usageVolumeDao.update(volumesVO);
        }
    }
}
Also used : Account(com.cloud.user.Account) List(java.util.List) ArrayList(java.util.ArrayList) SearchCriteria(com.cloud.utils.db.SearchCriteria)

Aggregations

SearchCriteria (com.cloud.utils.db.SearchCriteria)33 List (java.util.List)25 Account (com.cloud.user.Account)17 ArrayList (java.util.ArrayList)16 TransactionStatus (com.cloud.utils.db.TransactionStatus)8 DB (com.cloud.utils.db.DB)7 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)5 Filter (com.cloud.utils.db.Filter)5 DomainVO (com.cloud.domain.DomainVO)4 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)3 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)3 TemplateFilter (com.cloud.template.VirtualMachineTemplate.TemplateFilter)3 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)3 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)3 Map (java.util.Map)3 DedicatedResourceVO (com.cloud.dc.DedicatedResourceVO)2 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)2 DetailVO (com.cloud.host.DetailVO)2 HostVO (com.cloud.host.HostVO)2 NoTransitionException (com.cloud.utils.fsm.NoTransitionException)2