Search in sources :

Example 41 with SearchCriteria

use of com.cloud.utils.db.SearchCriteria in project cosmic by MissionCriticalCloud.

the class HostDetailsDaoImpl method deleteDetails.

@Override
public void deleteDetails(final long hostId) {
    final SearchCriteria sc = HostSearch.create();
    sc.setParameters("hostId", hostId);
    final List<DetailVO> results = search(sc, null);
    for (final DetailVO result : results) {
        remove(result.getId());
    }
}
Also used : DetailVO(com.cloud.host.DetailVO) SearchCriteria(com.cloud.utils.db.SearchCriteria)

Example 42 with SearchCriteria

use of com.cloud.utils.db.SearchCriteria in project cosmic by MissionCriticalCloud.

the class ResourceLimitManagerImpl method checkResourceLimit.

@Override
@DB
public void checkResourceLimit(final Account account, final ResourceType type, final long... count) throws ResourceAllocationException {
    final long numResources = ((count.length == 0) ? 1 : count[0]);
    Project project = null;
    // Don't place any limits on system or root admin accounts
    if (_accountMgr.isRootAdmin(account.getId())) {
        return;
    }
    if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) {
        project = _projectDao.findByProjectAccountId(account.getId());
    }
    final Project projectFinal = project;
    Transaction.execute(new TransactionCallbackWithExceptionNoReturn<ResourceAllocationException>() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) throws ResourceAllocationException {
            // Lock all rows first so nobody else can read it
            final Set<Long> rowIdsToLock = _resourceCountDao.listAllRowsToUpdate(account.getId(), ResourceOwnerType.Account, type);
            final SearchCriteria<ResourceCountVO> sc = ResourceCountSearch.create();
            sc.setParameters("id", rowIdsToLock.toArray());
            _resourceCountDao.lockRows(sc, null, true);
            // Check account limits
            final long accountLimit = findCorrectResourceLimitForAccount(account, type);
            final long potentialCount = _resourceCountDao.getResourceCount(account.getId(), ResourceOwnerType.Account, type) + numResources;
            if (accountLimit != Resource.RESOURCE_UNLIMITED && potentialCount > accountLimit) {
                String message = "Maximum number of resources of type '" + type + "' for account name=" + account.getAccountName() + " in domain id=" + account.getDomainId() + " has been exceeded.";
                if (projectFinal != null) {
                    message = "Maximum number of resources of type '" + type + "' for project name=" + projectFinal.getName() + " in domain id=" + account.getDomainId() + " has been exceeded.";
                }
                final ResourceAllocationException e = new ResourceAllocationException(message, type);
                s_logger.error(message, e);
                throw e;
            }
            // check all domains in the account's domain hierarchy
            Long domainId;
            if (projectFinal != null) {
                domainId = projectFinal.getDomainId();
            } else {
                domainId = account.getDomainId();
            }
            while (domainId != null) {
                final DomainVO domain = _domainDao.findById(domainId);
                // no limit check if it is ROOT domain
                if (domainId != Domain.ROOT_DOMAIN) {
                    final long domainLimit = findCorrectResourceLimitForDomain(domain, type);
                    final long domainCount = _resourceCountDao.getResourceCount(domainId, ResourceOwnerType.Domain, type) + numResources;
                    if (domainLimit != Resource.RESOURCE_UNLIMITED && domainCount > domainLimit) {
                        throw new ResourceAllocationException("Maximum number of resources of type '" + type + "' for domain id=" + domainId + " has been exceeded.", type);
                    }
                }
                domainId = domain.getParent();
            }
        }
    });
}
Also used : Project(com.cloud.projects.Project) DomainVO(com.cloud.domain.DomainVO) Set(java.util.Set) TransactionStatus(com.cloud.utils.db.TransactionStatus) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) SearchCriteria(com.cloud.utils.db.SearchCriteria) DB(com.cloud.utils.db.DB)

Example 43 with SearchCriteria

use of com.cloud.utils.db.SearchCriteria in project cosmic by MissionCriticalCloud.

the class AsyncJobManagerImpl method wakeupScan.

@DB
protected List<Long> wakeupScan() {
    final Date cutDate = DateUtil.currentGMTTime();
    final SearchCriteria<Long> sc = JoinJobTimeSearch.create();
    sc.setParameters("beginTime", cutDate);
    sc.setParameters("endTime", cutDate);
    final List<Long> result = _joinMapDao.customSearch(sc, null);
    return Transaction.execute(new TransactionCallback<List<Long>>() {

        @Override
        public List<Long> doInTransaction(final TransactionStatus status) {
            if (result.size() > 0) {
                Collections.sort(result);
                final Long[] ids = result.toArray(new Long[result.size()]);
                final AsyncJobVO job = _jobDao.createForUpdate();
                job.setPendingSignals(AsyncJob.Constants.SIGNAL_MASK_WAKEUP);
                final SearchCriteria<AsyncJobVO> sc2 = JobIdsSearch.create("ids", ids);
                final SearchCriteria<SyncQueueItemVO> queueItemsSC = QueueJobIdsSearch.create("contentIds", ids);
                _jobDao.update(job, sc2);
                final SyncQueueItemVO item = _queueItemDao.createForUpdate();
                item.setLastProcessNumber(null);
                item.setLastProcessMsid(null);
                _queueItemDao.update(item, queueItemsSC);
            }
            return _joinMapDao.findJobsToWakeBetween(cutDate);
        }
    });
}
Also used : TransactionStatus(com.cloud.utils.db.TransactionStatus) List(java.util.List) Date(java.util.Date) SearchCriteria(com.cloud.utils.db.SearchCriteria) DB(com.cloud.utils.db.DB)

Example 44 with SearchCriteria

use of com.cloud.utils.db.SearchCriteria in project cosmic by MissionCriticalCloud.

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");
    final long hostId = userVm.getHostId();
    final List<String> vmNames = new ArrayList<>();
    vmNames.add(userVm.getInstanceName());
    final HostVO host = _hostDao.findById(hostId);
    final GetVmDiskStatsAnswer diskStatsAnswer;
    try {
        diskStatsAnswer = (GetVmDiskStatsAnswer) _agentMgr.easySend(hostId, new GetVmDiskStatsCommand(vmNames, host.getGuid(), host.getName()));
    } catch (final 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(final TransactionStatus status) {
                    final HashMap<String, List<VmDiskStatsEntry>> vmDiskStatsByName = diskStatsAnswerFinal.getVmDiskStatsMap();
                    if (vmDiskStatsByName == null) {
                        return;
                    }
                    final List<VmDiskStatsEntry> vmDiskStats = vmDiskStatsByName.get(userVm.getInstanceName());
                    if (vmDiskStats == null) {
                        return;
                    }
                    for (final VmDiskStatsEntry vmDiskStat : vmDiskStats) {
                        final SearchCriteria<VolumeVO> sc_volume = _volsDao.createSearchCriteria();
                        sc_volume.addAnd("path", SearchCriteria.Op.EQ, vmDiskStat.getPath());
                        final List<VolumeVO> volumes = _volsDao.search(sc_volume, null);
                        if (volumes == null || volumes.size() == 0) {
                            break;
                        }
                        final VolumeVO volume = volumes.get(0);
                        final VmDiskStatisticsVO previousVmDiskStats = _vmDiskStatsDao.findBy(userVm.getAccountId(), userVm.getDataCenterId(), userVm.getId(), volume.getId());
                        final 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 (final 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) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ConcurrentOperationException(com.cloud.exception.ConcurrentOperationException) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) 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 45 with SearchCriteria

use of com.cloud.utils.db.SearchCriteria in project cosmic by MissionCriticalCloud.

the class UserVmManagerImpl method addInstanceToGroup.

@Override
@DB
public boolean addInstanceToGroup(final long userVmId, final String groupName) {
    final UserVmVO vm = _vmDao.findById(userVmId);
    InstanceGroupVO group = _vmGroupDao.findByAccountAndName(vm.getAccountId(), groupName);
    // Create vm group if the group doesn't exist for this account
    if (group == null) {
        group = createVmGroup(groupName, vm.getAccountId());
    }
    if (group != null) {
        final UserVm userVm = _vmDao.acquireInLockTable(userVmId);
        if (userVm == null) {
            s_logger.warn("Failed to acquire lock on user vm id=" + userVmId);
        }
        try {
            final InstanceGroupVO groupFinal = group;
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    // don't let the group be deleted when we are assigning vm to
                    // it.
                    final InstanceGroupVO ngrpLock = _vmGroupDao.lockRow(groupFinal.getId(), false);
                    if (ngrpLock == null) {
                        s_logger.warn("Failed to acquire lock on vm group id=" + groupFinal.getId() + " name=" + groupFinal.getName());
                        throw new CloudRuntimeException("Failed to acquire lock on vm group id=" + groupFinal.getId() + " name=" + groupFinal.getName());
                    }
                    // Currently don't allow to assign a vm to more than one group
                    if (_groupVMMapDao.listByInstanceId(userVmId) != null) {
                        // Delete all mappings from group_vm_map table
                        final List<InstanceGroupVMMapVO> groupVmMaps = _groupVMMapDao.listByInstanceId(userVmId);
                        for (final InstanceGroupVMMapVO groupMap : groupVmMaps) {
                            final SearchCriteria<InstanceGroupVMMapVO> sc = _groupVMMapDao.createSearchCriteria();
                            sc.addAnd("instanceId", SearchCriteria.Op.EQ, groupMap.getInstanceId());
                            _groupVMMapDao.expunge(sc);
                        }
                    }
                    final InstanceGroupVMMapVO groupVmMapVO = new InstanceGroupVMMapVO(groupFinal.getId(), userVmId);
                    _groupVMMapDao.persist(groupVmMapVO);
                }
            });
            return true;
        } finally {
            if (userVm != null) {
                _vmDao.releaseFromLockTable(userVmId);
            }
        }
    }
    return false;
}
Also used : UserVm(com.cloud.uservm.UserVm) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ArrayList(java.util.ArrayList) ExcludeList(com.cloud.deploy.DeploymentPlanner.ExcludeList) List(java.util.List) SearchCriteria(com.cloud.utils.db.SearchCriteria) DB(com.cloud.utils.db.DB)

Aggregations

SearchCriteria (com.cloud.utils.db.SearchCriteria)54 List (java.util.List)40 ArrayList (java.util.ArrayList)31 Account (com.cloud.user.Account)23 TransactionStatus (com.cloud.utils.db.TransactionStatus)18 DB (com.cloud.utils.db.DB)13 DomainVO (com.cloud.domain.DomainVO)12 Filter (com.cloud.utils.db.Filter)12 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)12 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)11 HashMap (java.util.HashMap)11 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)10 ExcludeList (com.cloud.deploy.DeploymentPlanner.ExcludeList)9 Map (java.util.Map)8 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)7 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)7 HostVO (com.cloud.host.HostVO)7 TemplateFilter (com.cloud.template.VirtualMachineTemplate.TemplateFilter)7 Pair (com.cloud.utils.Pair)6 NoTransitionException (com.cloud.utils.fsm.NoTransitionException)6