Search in sources :

Example 26 with TransactionCallbackNoReturn

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

the class ResourceManagerImpl method doDeleteHost.

@DB
protected boolean doDeleteHost(final long hostId, final boolean isForced, final boolean isForceDeleteStorage) {
    _accountMgr.getActiveUser(CallContext.current().getCallingUserId());
    // Verify that host exists
    final HostVO host = _hostDao.findById(hostId);
    if (host == null) {
        throw new InvalidParameterValueException("Host with id " + hostId + " doesn't exist");
    }
    _accountMgr.checkAccessAndSpecifyAuthority(CallContext.current().getCallingAccount(), host.getDataCenterId());
    if (!isForced && host.getResourceState() != ResourceState.Maintenance) {
        throw new CloudRuntimeException("Host " + host.getUuid() + " cannot be deleted as it is not in maintenance mode. Either put the host into maintenance or perform a forced deletion.");
    }
    // Get storage pool host mappings here because they can be removed as a
    // part of handleDisconnect later
    // TODO: find out the bad boy, what's a buggy logic!
    final List<StoragePoolHostVO> pools = _storagePoolHostDao.listByHostIdIncludingRemoved(hostId);
    final ResourceStateAdapter.DeleteHostAnswer answer = (ResourceStateAdapter.DeleteHostAnswer) dispatchToStateAdapters(ResourceStateAdapter.Event.DELETE_HOST, false, host, isForced, isForceDeleteStorage);
    if (answer == null) {
        throw new CloudRuntimeException("No resource adapter respond to DELETE_HOST event for " + host.getName() + " id = " + hostId + ", hypervisorType is " + host.getHypervisorType() + ", host type is " + host.getType());
    }
    if (answer.getIsException()) {
        return false;
    }
    if (!answer.getIsContinue()) {
        return true;
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            _dcDao.releasePrivateIpAddress(host.getPrivateIpAddress(), host.getDataCenterId(), null);
            _agentMgr.disconnectWithoutInvestigation(hostId, Status.Event.Remove);
            // delete host details
            _hostDetailsDao.deleteDetails(hostId);
            // if host is GPU enabled, delete GPU entries
            _hostGpuGroupsDao.deleteGpuEntries(hostId);
            // delete host tags
            _hostTagsDao.deleteTags(hostId);
            host.setGuid(null);
            final Long clusterId = host.getClusterId();
            host.setClusterId(null);
            _hostDao.update(host.getId(), host);
            _hostDao.remove(hostId);
            if (clusterId != null) {
                final List<HostVO> hosts = listAllHostsInCluster(clusterId);
                if (hosts.size() == 0) {
                    final ClusterVO cluster = _clusterDao.findById(clusterId);
                    cluster.setGuid(null);
                    _clusterDao.update(clusterId, cluster);
                }
            }
            try {
                resourceStateTransitTo(host, ResourceState.Event.DeleteHost, _nodeId);
            } catch (final NoTransitionException e) {
                s_logger.debug("Cannot transmit host " + host.getId() + " to Enabled state", e);
            }
            // Delete the associated entries in host ref table
            _storagePoolHostDao.deletePrimaryRecordsForHost(hostId);
            // Make sure any VMs that were marked as being on this host are cleaned up
            final List<VMInstanceVO> vms = _vmDao.listByHostId(hostId);
            for (final VMInstanceVO vm : vms) {
                // this is how VirtualMachineManagerImpl does it when it syncs VM states
                vm.setState(State.Stopped);
                vm.setHostId(null);
                _vmDao.persist(vm);
            }
            // where
            for (final StoragePoolHostVO pool : pools) {
                final Long poolId = pool.getPoolId();
                final StoragePoolVO storagePool = _storagePoolDao.findById(poolId);
                if (storagePool.isLocal() && isForceDeleteStorage) {
                    storagePool.setUuid(null);
                    storagePool.setClusterId(null);
                    _storagePoolDao.update(poolId, storagePool);
                    _storagePoolDao.remove(poolId);
                    s_logger.debug("Local storage id=" + poolId + " is removed as a part of host removal id=" + hostId);
                }
            }
            // delete the op_host_capacity entry
            final Object[] capacityTypes = { Capacity.CAPACITY_TYPE_CPU, Capacity.CAPACITY_TYPE_MEMORY };
            final SearchCriteria<CapacityVO> hostCapacitySC = _capacityDao.createSearchCriteria();
            hostCapacitySC.addAnd("hostOrPoolId", SearchCriteria.Op.EQ, hostId);
            hostCapacitySC.addAnd("capacityType", SearchCriteria.Op.IN, capacityTypes);
            _capacityDao.remove(hostCapacitySC);
            // remove from dedicated resources
            final DedicatedResourceVO dr = _dedicatedDao.findByHostId(hostId);
            if (dr != null) {
                _dedicatedDao.remove(dr.getId());
            }
        }
    });
    return true;
}
Also used : ClusterVO(com.cloud.dc.ClusterVO) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) VMInstanceVO(com.cloud.vm.VMInstanceVO) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) StoragePoolHostVO(com.cloud.storage.StoragePoolHostVO) HostVO(com.cloud.host.HostVO) SearchCriteria(com.cloud.utils.db.SearchCriteria) InvalidParameterValueException(com.cloud.utils.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) NoTransitionException(com.cloud.utils.fsm.NoTransitionException) StoragePoolVO(com.cloud.storage.datastore.db.StoragePoolVO) ArrayList(java.util.ArrayList) List(java.util.List) DedicatedResourceVO(com.cloud.dc.DedicatedResourceVO) DB(com.cloud.utils.db.DB)

Example 27 with TransactionCallbackNoReturn

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

the class ConfigurationServerImpl method generateSecStorageVmCopyPassword.

@DB
protected void generateSecStorageVmCopyPassword() {
    final String already = _configDao.getValue("secstorage.copy.password");
    if (already == null) {
        s_logger.info("Need to store secondary storage vm copy password in the database");
        final String password = PasswordGenerator.generateRandomPassword(12);
        final String insertSql1 = "INSERT INTO `cloud`.`configuration` (category, instance, component, name, value, description) " + "VALUES ('Hidden','DEFAULT', 'management-server','secstorage.copy.password', '" + DBEncryptionUtil.encrypt(password) + "','Password used to authenticate zone-to-zone template copy requests')";
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(final TransactionStatus status) {
                final TransactionLegacy txn = TransactionLegacy.currentTxn();
                try {
                    final PreparedStatement stmt1 = txn.prepareAutoCloseStatement(insertSql1);
                    stmt1.executeUpdate();
                    s_logger.debug("secondary storage vm copy password inserted into database");
                } catch (final SQLException ex) {
                    s_logger.warn("Failed to insert secondary storage vm copy password", ex);
                }
            }
        });
    }
}
Also used : TransactionLegacy(com.cloud.utils.db.TransactionLegacy) SQLException(java.sql.SQLException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) PreparedStatement(java.sql.PreparedStatement) DB(com.cloud.utils.db.DB)

Example 28 with TransactionCallbackNoReturn

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

the class ConfigurationServerImpl method updateResourceCount.

@DB
public void updateResourceCount() {
    final ResourceType[] resourceTypes = Resource.ResourceType.values();
    final List<AccountVO> accounts = _accountDao.listAll();
    final List<DomainVO> domains = _domainDao.listAll();
    final List<ResourceCountVO> domainResourceCount = _resourceCountDao.listResourceCountByOwnerType(ResourceOwnerType.Domain);
    final List<ResourceCountVO> accountResourceCount = _resourceCountDao.listResourceCountByOwnerType(ResourceOwnerType.Account);
    final List<ResourceType> accountSupportedResourceTypes = new ArrayList<>();
    final List<ResourceType> domainSupportedResourceTypes = new ArrayList<>();
    for (final ResourceType resourceType : resourceTypes) {
        if (resourceType.supportsOwner(ResourceOwnerType.Account)) {
            accountSupportedResourceTypes.add(resourceType);
        }
        if (resourceType.supportsOwner(ResourceOwnerType.Domain)) {
            domainSupportedResourceTypes.add(resourceType);
        }
    }
    final int accountExpectedCount = accountSupportedResourceTypes.size();
    final int domainExpectedCount = domainSupportedResourceTypes.size();
    if ((domainResourceCount.size() < domainExpectedCount * domains.size())) {
        s_logger.debug("resource_count table has records missing for some domains...going to insert them");
        for (final DomainVO domain : domains) {
            // Lock domain
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    _domainDao.lockRow(domain.getId(), true);
                    final List<ResourceCountVO> domainCounts = _resourceCountDao.listByOwnerId(domain.getId(), ResourceOwnerType.Domain);
                    final List<String> domainCountStr = new ArrayList<>();
                    for (final ResourceCountVO domainCount : domainCounts) {
                        domainCountStr.add(domainCount.getType().toString());
                    }
                    if (domainCountStr.size() < domainExpectedCount) {
                        for (final ResourceType resourceType : domainSupportedResourceTypes) {
                            if (!domainCountStr.contains(resourceType.toString())) {
                                final ResourceCountVO resourceCountVO = new ResourceCountVO(resourceType, 0, domain.getId(), ResourceOwnerType.Domain);
                                s_logger.debug("Inserting resource count of type " + resourceType + " for domain id=" + domain.getId());
                                _resourceCountDao.persist(resourceCountVO);
                            }
                        }
                    }
                }
            });
        }
    }
    if ((accountResourceCount.size() < accountExpectedCount * accounts.size())) {
        s_logger.debug("resource_count table has records missing for some accounts...going to insert them");
        for (final AccountVO account : accounts) {
            // lock account
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(final TransactionStatus status) {
                    _accountDao.lockRow(account.getId(), true);
                    final List<ResourceCountVO> accountCounts = _resourceCountDao.listByOwnerId(account.getId(), ResourceOwnerType.Account);
                    final List<String> accountCountStr = new ArrayList<>();
                    for (final ResourceCountVO accountCount : accountCounts) {
                        accountCountStr.add(accountCount.getType().toString());
                    }
                    if (accountCountStr.size() < accountExpectedCount) {
                        for (final ResourceType resourceType : accountSupportedResourceTypes) {
                            if (!accountCountStr.contains(resourceType.toString())) {
                                final ResourceCountVO resourceCountVO = new ResourceCountVO(resourceType, 0, account.getId(), ResourceOwnerType.Account);
                                s_logger.debug("Inserting resource count of type " + resourceType + " for account id=" + account.getId());
                                _resourceCountDao.persist(resourceCountVO);
                            }
                        }
                    }
                }
            });
        }
    }
}
Also used : ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) ResourceType(com.cloud.configuration.Resource.ResourceType) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) AccountVO(com.cloud.user.AccountVO) DomainVO(com.cloud.domain.DomainVO) ResourceCountVO(com.cloud.configuration.ResourceCountVO) List(java.util.List) ArrayList(java.util.ArrayList) DB(com.cloud.utils.db.DB)

Example 29 with TransactionCallbackNoReturn

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

the class VpcManagerImpl method revokeStaticRoutesForVpc.

@DB
private boolean revokeStaticRoutesForVpc(final long vpcId, final Account caller) throws ResourceUnavailableException {
    // get all static routes for the vpc
    final List<StaticRouteVO> routes = _staticRouteDao.listByVpcId(vpcId);
    s_logger.debug("Found " + routes.size() + " to revoke for the vpc " + vpcId);
    if (!routes.isEmpty()) {
        // mark all of them as revoke
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(final TransactionStatus status) {
                for (final StaticRouteVO route : routes) {
                    markStaticRouteForRevoke(route, caller);
                }
            }
        });
        return applyStaticRoutesForVpc(vpcId);
    }
    return true;
}
Also used : TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) DB(com.cloud.utils.db.DB)

Example 30 with TransactionCallbackNoReturn

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

the class VpcPrivateGatewayTransactionCallable method call.

@Override
public Boolean call() throws Exception {
    final long networkId = gateway.getNetworkId();
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            final List<PrivateIpVO> privateIps = _privateIpDao.listByNetworkId(networkId);
            if (privateIps.size() > 1 || !privateIps.get(0).getIpAddress().equalsIgnoreCase(gateway.getIp4Address())) {
                s_logger.debug("Not removing network id=" + gateway.getNetworkId() + " as it has private ip addresses for other gateways");
                deleteNetwork = false;
            }
            final PrivateIpVO ip = _privateIpDao.findByIpAndVpcId(gateway.getVpcId(), gateway.getIp4Address());
            if (ip != null) {
                _privateIpDao.remove(ip.getId());
                s_logger.debug("Deleted private ip " + ip);
            }
            _vpcGatewayDao.remove(gateway.getId());
            s_logger.debug("Deleted private gateway " + gateway);
        }
    });
    return deleteNetwork;
}
Also used : TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) List(java.util.List)

Aggregations

TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)172 TransactionStatus (com.cloud.utils.db.TransactionStatus)172 DB (com.cloud.utils.db.DB)133 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)71 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)60 ArrayList (java.util.ArrayList)57 ActionEvent (com.cloud.event.ActionEvent)42 List (java.util.List)42 Account (com.cloud.user.Account)39 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)38 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)36 ConfigurationException (javax.naming.ConfigurationException)32 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)26 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)24 IPAddressVO (com.cloud.network.dao.IPAddressVO)24 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)23 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)18 HostVO (com.cloud.host.HostVO)18 HashMap (java.util.HashMap)18 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)17