Search in sources :

Example 66 with TransactionCallbackNoReturn

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

the class CapacityManagerImpl method releaseVmCapacity.

@DB
@Override
public boolean releaseVmCapacity(VirtualMachine vm, final boolean moveFromReserved, final boolean moveToReservered, final Long hostId) {
    if (hostId == null) {
        return true;
    }
    final ServiceOfferingVO svo = _offeringsDao.findById(vm.getId(), vm.getServiceOfferingId());
    CapacityVO capacityCpu = _capacityDao.findByHostIdType(hostId, Capacity.CAPACITY_TYPE_CPU);
    CapacityVO capacityMemory = _capacityDao.findByHostIdType(hostId, Capacity.CAPACITY_TYPE_MEMORY);
    Long clusterId = null;
    if (hostId != null) {
        HostVO host = _hostDao.findById(hostId);
        if (host == null) {
            s_logger.warn("Host " + hostId + " no long exist anymore!");
            return true;
        }
        clusterId = host.getClusterId();
    }
    if (capacityCpu == null || capacityMemory == null || svo == null) {
        return false;
    }
    try {
        final Long clusterIdFinal = clusterId;
        final long capacityCpuId = capacityCpu.getId();
        final long capacityMemoryId = capacityMemory.getId();
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                CapacityVO capacityCpu = _capacityDao.lockRow(capacityCpuId, true);
                CapacityVO capacityMemory = _capacityDao.lockRow(capacityMemoryId, true);
                long usedCpu = capacityCpu.getUsedCapacity();
                long usedMem = capacityMemory.getUsedCapacity();
                long reservedCpu = capacityCpu.getReservedCapacity();
                long reservedMem = capacityMemory.getReservedCapacity();
                long actualTotalCpu = capacityCpu.getTotalCapacity();
                float cpuOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterIdFinal, "cpuOvercommitRatio").getValue());
                float memoryOvercommitRatio = Float.parseFloat(_clusterDetailsDao.findDetail(clusterIdFinal, "memoryOvercommitRatio").getValue());
                int vmCPU = svo.getCpu() * svo.getSpeed();
                long vmMem = svo.getRamSize() * 1024L * 1024L;
                long actualTotalMem = capacityMemory.getTotalCapacity();
                long totalMem = (long) (actualTotalMem * memoryOvercommitRatio);
                long totalCpu = (long) (actualTotalCpu * cpuOvercommitRatio);
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Hosts's actual total CPU: " + actualTotalCpu + " and CPU after applying overprovisioning: " + totalCpu);
                    s_logger.debug("Hosts's actual total RAM: " + actualTotalMem + " and RAM after applying overprovisioning: " + totalMem);
                }
                if (!moveFromReserved) {
                    /* move resource from used */
                    if (usedCpu >= vmCPU) {
                        capacityCpu.setUsedCapacity(usedCpu - vmCPU);
                    }
                    if (usedMem >= vmMem) {
                        capacityMemory.setUsedCapacity(usedMem - vmMem);
                    }
                    if (moveToReservered) {
                        if (reservedCpu + vmCPU <= totalCpu) {
                            capacityCpu.setReservedCapacity(reservedCpu + vmCPU);
                        }
                        if (reservedMem + vmMem <= totalMem) {
                            capacityMemory.setReservedCapacity(reservedMem + vmMem);
                        }
                    }
                } else {
                    if (reservedCpu >= vmCPU) {
                        capacityCpu.setReservedCapacity(reservedCpu - vmCPU);
                    }
                    if (reservedMem >= vmMem) {
                        capacityMemory.setReservedCapacity(reservedMem - vmMem);
                    }
                }
                s_logger.debug("release cpu from host: " + hostId + ", old used: " + usedCpu + ",reserved: " + reservedCpu + ", actual total: " + actualTotalCpu + ", total with overprovisioning: " + totalCpu + "; new used: " + capacityCpu.getUsedCapacity() + ",reserved:" + capacityCpu.getReservedCapacity() + "; movedfromreserved: " + moveFromReserved + ",moveToReservered" + moveToReservered);
                s_logger.debug("release mem from host: " + hostId + ", old used: " + usedMem + ",reserved: " + reservedMem + ", total: " + totalMem + "; new used: " + capacityMemory.getUsedCapacity() + ",reserved:" + capacityMemory.getReservedCapacity() + "; movedfromreserved: " + moveFromReserved + ",moveToReservered" + moveToReservered);
                _capacityDao.update(capacityCpu.getId(), capacityCpu);
                _capacityDao.update(capacityMemory.getId(), capacityMemory);
            }
        });
        return true;
    } catch (Exception e) {
        s_logger.debug("Failed to transit vm's state, due to " + e.getMessage());
        return false;
    }
}
Also used : TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) ServiceOfferingVO(com.cloud.service.ServiceOfferingVO) HostVO(com.cloud.host.HostVO) ConnectionException(com.cloud.exception.ConnectionException) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) DB(com.cloud.utils.db.DB)

Example 67 with TransactionCallbackNoReturn

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

the class StorageNetworkManagerImpl method updateIpRange.

@Override
@DB
public StorageNetworkIpRange updateIpRange(UpdateStorageNetworkIpRangeCmd cmd) {
    final Integer vlan = cmd.getVlan();
    final Long rangeId = cmd.getId();
    String startIp = cmd.getStartIp();
    String endIp = cmd.getEndIp();
    final String netmask = cmd.getNetmask();
    if (netmask != null && !NetUtils.isValidNetmask(netmask)) {
        throw new CloudRuntimeException("Invalid netmask:" + netmask);
    }
    if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) {
        throw new CloudRuntimeException("Cannot update the range," + getInUseIpAddress(rangeId));
    }
    StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId);
    if (range == null) {
        throw new CloudRuntimeException("Cannot find storage ip range " + rangeId);
    }
    if (startIp != null || endIp != null) {
        long podId = range.getPodId();
        startIp = startIp == null ? range.getStartIp() : startIp;
        endIp = endIp == null ? range.getEndIp() : endIp;
        checkOverlapPrivateIpRange(podId, startIp, endIp);
        checkOverlapStorageIpRange(podId, startIp, endIp);
    }
    final String startIpFinal = startIp;
    final String endIpFinal = endIp;
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            StorageNetworkIpRangeVO range = null;
            try {
                range = _sNwIpRangeDao.acquireInLockTable(rangeId);
                if (range == null) {
                    throw new CloudRuntimeException("Cannot acquire lock on storage ip range " + rangeId);
                }
                StorageNetworkIpRangeVO vo = _sNwIpRangeDao.createForUpdate();
                if (vlan != null) {
                    vo.setVlan(vlan);
                }
                if (startIpFinal != null) {
                    vo.setStartIp(startIpFinal);
                }
                if (endIpFinal != null) {
                    vo.setEndIp(endIpFinal);
                }
                if (netmask != null) {
                    vo.setNetmask(netmask);
                }
                _sNwIpRangeDao.update(rangeId, vo);
            } finally {
                if (range != null) {
                    _sNwIpRangeDao.releaseFromLockTable(range.getId());
                }
            }
        }
    });
    return _sNwIpRangeDao.findById(rangeId);
}
Also used : StorageNetworkIpRangeVO(com.cloud.dc.StorageNetworkIpRangeVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) DB(com.cloud.utils.db.DB)

Example 68 with TransactionCallbackNoReturn

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

the class StorageNetworkManagerImpl method deleteIpRange.

@Override
@DB
public void deleteIpRange(DeleteStorageNetworkIpRangeCmd cmd) {
    final long rangeId = cmd.getId();
    StorageNetworkIpRangeVO range = _sNwIpRangeDao.findById(rangeId);
    if (range == null) {
        throw new CloudRuntimeException("Can not find storage network ip range " + rangeId);
    }
    if (_sNwIpDao.countInUseIpByRangeId(rangeId) > 0) {
        throw new CloudRuntimeException(getInUseIpAddress(rangeId));
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            StorageNetworkIpRangeVO range = null;
            try {
                range = _sNwIpRangeDao.acquireInLockTable(rangeId);
                if (range == null) {
                    String msg = "Unable to acquire lock on storage network ip range id=" + rangeId + ", delete failed";
                    s_logger.warn(msg);
                    throw new CloudRuntimeException(msg);
                }
                /*
                     * entries in op_dc_storage_network_ip_address will be deleted automatically due to
                     * fk_storage_ip_address__range_id constraint key
                     */
                _sNwIpRangeDao.remove(rangeId);
            } finally {
                if (range != null) {
                    _sNwIpRangeDao.releaseFromLockTable(rangeId);
                }
            }
        }
    });
}
Also used : StorageNetworkIpRangeVO(com.cloud.dc.StorageNetworkIpRangeVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) DB(com.cloud.utils.db.DB)

Example 69 with TransactionCallbackNoReturn

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

the class GlobalLoadBalancingRulesServiceImpl method removeFromGlobalLoadBalancerRule.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_REMOVE_FROM_GLOBAL_LOAD_BALANCER_RULE, eventDescription = "Removing a load balancer rule to be part of global load balancer rule")
public boolean removeFromGlobalLoadBalancerRule(RemoveFromGlobalLoadBalancerRuleCmd removeFromGslbCmd) {
    CallContext ctx = CallContext.current();
    Account caller = ctx.getCallingAccount();
    final long gslbRuleId = removeFromGslbCmd.getGlobalLoadBalancerRuleId();
    final GlobalLoadBalancerRuleVO gslbRule = _gslbRuleDao.findById(gslbRuleId);
    if (gslbRule == null) {
        throw new InvalidParameterValueException("Invalid global load balancer rule id: " + gslbRuleId);
    }
    _accountMgr.checkAccess(caller, SecurityChecker.AccessType.OperateEntry, true, gslbRule);
    if (gslbRule.getState() == GlobalLoadBalancerRule.State.Revoke) {
        throw new InvalidParameterValueException("global load balancer rule id: " + gslbRuleId + " is already in revoked state");
    }
    final List<Long> lbRuleIdsToremove = removeFromGslbCmd.getLoadBalancerRulesIds();
    if (lbRuleIdsToremove == null || lbRuleIdsToremove.isEmpty()) {
        throw new InvalidParameterValueException("empty list of load balancer rule Ids specified to be un-assigned" + " to global load balancer rule");
    }
    // get the active list of LB rule id's that are assigned currently to GSLB rule and corresponding zone id's
    List<Long> oldLbRuleIds = new ArrayList<Long>();
    List<Long> oldZones = new ArrayList<Long>();
    List<GlobalLoadBalancerLbRuleMapVO> gslbLbMapVos = _gslbLbMapDao.listByGslbRuleId(gslbRuleId);
    if (gslbLbMapVos == null) {
        throw new InvalidParameterValueException(" There are no load balancer rules that are assigned to global " + " load balancer rule id: " + gslbRule.getUuid() + " that are available for deletion");
    }
    for (Long lbRuleId : lbRuleIdsToremove) {
        LoadBalancerVO loadBalancer = _lbDao.findById(lbRuleId);
        if (loadBalancer == null) {
            throw new InvalidParameterValueException("Specified load balancer rule ID does not exist.");
        }
        _accountMgr.checkAccess(caller, null, true, loadBalancer);
    }
    for (GlobalLoadBalancerLbRuleMapVO gslbLbMapVo : gslbLbMapVos) {
        LoadBalancerVO loadBalancer = _lbDao.findById(gslbLbMapVo.getLoadBalancerId());
        Network network = _networkDao.findById(loadBalancer.getNetworkId());
        oldLbRuleIds.add(gslbLbMapVo.getLoadBalancerId());
        oldZones.add(network.getDataCenterId());
    }
    for (Long lbRuleId : lbRuleIdsToremove) {
        LoadBalancerVO loadBalancer = _lbDao.findById(lbRuleId);
        if (oldLbRuleIds != null && !oldLbRuleIds.contains(loadBalancer.getId())) {
            throw new InvalidParameterValueException("Load balancer ID " + loadBalancer.getUuid() + " is not assigned" + " to global load balancer rule: " + gslbRule.getUuid());
        }
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            // update the mapping of gslb rule to Lb rule, to revoke state
            for (Long lbRuleId : lbRuleIdsToremove) {
                GlobalLoadBalancerLbRuleMapVO removeGslbLbMap = _gslbLbMapDao.findByGslbRuleIdAndLbRuleId(gslbRuleId, lbRuleId);
                removeGslbLbMap.setRevoke(true);
                _gslbLbMapDao.update(removeGslbLbMap.getId(), removeGslbLbMap);
            }
            // mark the gslb rule state as add
            if (gslbRule.getState() == GlobalLoadBalancerRule.State.Staged) {
                gslbRule.setState(GlobalLoadBalancerRule.State.Add);
                _gslbRuleDao.update(gslbRule.getId(), gslbRule);
            }
        }
    });
    boolean success = false;
    try {
        s_logger.debug("Attempting to configure global load balancer rule configuration on the gslb service providers ");
        // apply the gslb rule on to the back end gslb service providers
        if (!applyGlobalLoadBalancerRuleConfig(gslbRuleId, false)) {
            s_logger.warn("Failed to remove load balancer rules " + lbRuleIdsToremove + " from global load balancer rule id " + gslbRuleId);
            CloudRuntimeException ex = new CloudRuntimeException("Failed to remove load balancer rule ids from GSLB rule ");
            throw ex;
        }
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                // remove the mappings of gslb rule to Lb rule that are in revoked state
                for (Long lbRuleId : lbRuleIdsToremove) {
                    GlobalLoadBalancerLbRuleMapVO removeGslbLbMap = _gslbLbMapDao.findByGslbRuleIdAndLbRuleId(gslbRuleId, lbRuleId);
                    _gslbLbMapDao.remove(removeGslbLbMap.getId());
                }
                // on success set state back to Active
                gslbRule.setState(GlobalLoadBalancerRule.State.Active);
                _gslbRuleDao.update(gslbRule.getId(), gslbRule);
            }
        });
        success = true;
    } catch (ResourceUnavailableException e) {
        throw new CloudRuntimeException("Failed to update removed load balancer details from gloabal load balancer");
    }
    return success;
}
Also used : Account(com.cloud.user.Account) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) CallContext(org.apache.cloudstack.context.CallContext) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 70 with TransactionCallbackNoReturn

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

the class BaremetaNetworkGuru method reserve.

@Override
public void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientVirtualNetworkCapacityException {
    if (dest.getHost().getHypervisorType() != HypervisorType.BareMetal) {
        super.reserve(nic, network, vm, dest, context);
        return;
    }
    HostVO host = _hostDao.findById(dest.getHost().getId());
    _hostDao.loadDetails(host);
    String intentIp = host.getDetail(ApiConstants.IP_ADDRESS);
    if (intentIp == null) {
        super.reserve(nic, network, vm, dest, context);
        return;
    }
    String oldIp = nic.getIPv4Address();
    boolean getNewIp = false;
    if (oldIp == null) {
        getNewIp = true;
    } else {
        // we need to get a new ip address if we try to deploy a vm in a
        // different pod
        final IPAddressVO ipVO = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), oldIp);
        if (ipVO != null) {
            PodVlanMapVO mapVO = _podVlanDao.listPodVlanMapsByVlan(ipVO.getVlanId());
            if (mapVO.getPodId() != dest.getPod().getId()) {
                Transaction.execute(new TransactionCallbackNoReturn() {

                    @Override
                    public void doInTransactionWithoutResult(TransactionStatus status) {
                        // release the old ip here
                        _ipAddrMgr.markIpAsUnavailable(ipVO.getId());
                        _ipAddressDao.unassignIpAddress(ipVO.getId());
                    }
                });
                nic.setIPv4Address(null);
                getNewIp = true;
            }
        }
    }
    if (getNewIp) {
        // we don't set reservationStrategy to Create because we need this
        // method to be called again for the case when vm fails to deploy in
        // Pod1, and we try to redeploy it in Pod2
        getBaremetalIp(nic, dest.getPod(), vm, network, intentIp);
    }
    DataCenter dc = _dcDao.findById(network.getDataCenterId());
    nic.setIPv4Dns1(dc.getDns1());
    nic.setIPv4Dns2(dc.getDns2());
    /*
         * Pod pod = dest.getPod(); Pair<String, Long> ip =
         * _dcDao.allocatePrivateIpAddress(dest.getDataCenter().getId(),
         * dest.getPod().getId(), nic.getId(), context.getReservationId(),
         * intentIp); if (ip == null) { throw new
         * InsufficientAddressCapacityException
         * ("Unable to get a management ip address", Pod.class, pod.getId()); }
         *
         * nic.setIp4Address(ip.first());
         * nic.setMacAddress(NetUtils.long2Mac(NetUtils
         * .createSequenceBasedMacAddress(ip.second())));
         * nic.setGateway(pod.getGateway()); nic.setFormat(AddressFormat.Ip4);
         * String netmask = NetUtils.getCidrNetmask(pod.getCidrSize());
         * nic.setNetmask(netmask);
         * nic.setBroadcastType(BroadcastDomainType.Native);
         * nic.setBroadcastUri(null); nic.setIsolationUri(null);
         */
    s_logger.debug("Allocated a nic " + nic + " for " + vm);
}
Also used : DataCenter(com.cloud.dc.DataCenter) PodVlanMapVO(com.cloud.dc.PodVlanMapVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) IPAddressVO(com.cloud.network.dao.IPAddressVO) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) HostVO(com.cloud.host.HostVO)

Aggregations

TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)93 TransactionStatus (com.cloud.utils.db.TransactionStatus)93 DB (com.cloud.utils.db.DB)73 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)50 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)34 ArrayList (java.util.ArrayList)30 List (java.util.List)21 ActionEvent (com.cloud.event.ActionEvent)20 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)19 Account (com.cloud.user.Account)18 ConfigurationException (javax.naming.ConfigurationException)15 IPAddressVO (com.cloud.network.dao.IPAddressVO)14 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)11 Network (com.cloud.network.Network)10 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)9 HostVO (com.cloud.host.HostVO)9 HashMap (java.util.HashMap)9 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)8 DataCenter (com.cloud.dc.DataCenter)7 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)7