Search in sources :

Example 46 with TransactionStatus

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

the class LoadBalancingRulesManagerImpl method assignToLoadBalancer.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_ASSIGN_TO_LOAD_BALANCER_RULE, eventDescription = "assigning to load balancer", async = true)
public boolean assignToLoadBalancer(long loadBalancerId, List<Long> instanceIds, Map<Long, List<String>> vmIdIpMap) {
    CallContext ctx = CallContext.current();
    Account caller = ctx.getCallingAccount();
    final LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId);
    if (loadBalancer == null) {
        throw new InvalidParameterValueException("Failed to assign to load balancer " + loadBalancerId + ", the load balancer was not found.");
    }
    if (instanceIds == null && vmIdIpMap.isEmpty()) {
        throw new InvalidParameterValueException("Both instanceids and vmidipmap  can't be null");
    }
    // instanceIds and vmIdipmap is passed
    if (instanceIds != null && !vmIdIpMap.isEmpty()) {
        for (long instanceId : instanceIds) {
            if (!vmIdIpMap.containsKey(instanceId)) {
                vmIdIpMap.put(instanceId, null);
            }
        }
    }
    //only instanceids list passed
    if (instanceIds != null && vmIdIpMap.isEmpty()) {
        vmIdIpMap = new HashMap<Long, List<String>>();
        for (long instanceId : instanceIds) {
            vmIdIpMap.put(instanceId, null);
        }
    }
    List<LoadBalancerVMMapVO> mappedInstances = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId, false);
    Set<Long> mappedInstanceIds = new HashSet<Long>();
    for (LoadBalancerVMMapVO mappedInstance : mappedInstances) {
        mappedInstanceIds.add(Long.valueOf(mappedInstance.getInstanceId()));
    }
    Map<Long, List<String>> existingVmIdIps = new HashMap<Long, List<String>>();
    // now get the ips of vm and add it to map
    for (LoadBalancerVMMapVO mappedInstance : mappedInstances) {
        List<String> ipsList = null;
        if (existingVmIdIps.containsKey(mappedInstance.getInstanceId())) {
            ipsList = existingVmIdIps.get(mappedInstance.getInstanceId());
        } else {
            ipsList = new ArrayList<String>();
        }
        ipsList.add(mappedInstance.getInstanceIp());
        existingVmIdIps.put(mappedInstance.getInstanceId(), ipsList);
    }
    final List<UserVm> vmsToAdd = new ArrayList<UserVm>();
    // check for conflict
    Set<Long> passedInstanceIds = vmIdIpMap.keySet();
    for (Long instanceId : passedInstanceIds) {
        UserVm vm = _vmDao.findById(instanceId);
        if (vm == null || vm.getState() == State.Destroyed || vm.getState() == State.Expunging) {
            InvalidParameterValueException ex = new InvalidParameterValueException("Invalid instance id specified");
            if (vm == null) {
                ex.addProxyObject(instanceId.toString(), "instanceId");
            } else {
                ex.addProxyObject(vm.getUuid(), "instanceId");
            }
            throw ex;
        }
        _rulesMgr.checkRuleAndUserVm(loadBalancer, vm, caller);
        if (vm.getAccountId() != loadBalancer.getAccountId()) {
            throw new PermissionDeniedException("Cannot add virtual machines that do not belong to the same owner.");
        }
        // Let's check to make sure the vm has a nic in the same network as
        // the load balancing rule.
        List<? extends Nic> nics = _networkModel.getNics(vm.getId());
        Nic nicInSameNetwork = null;
        for (Nic nic : nics) {
            if (nic.getNetworkId() == loadBalancer.getNetworkId()) {
                nicInSameNetwork = nic;
                break;
            }
        }
        if (nicInSameNetwork == null) {
            InvalidParameterValueException ex = new InvalidParameterValueException("VM with id specified cannot be added because it doesn't belong in the same network.");
            ex.addProxyObject(vm.getUuid(), "instanceId");
            throw ex;
        }
        String priIp = nicInSameNetwork.getIPv4Address();
        if (existingVmIdIps.containsKey(instanceId)) {
            // now check for ip address
            List<String> mappedIps = existingVmIdIps.get(instanceId);
            List<String> newIps = vmIdIpMap.get(instanceId);
            if (newIps == null) {
                newIps = new ArrayList<String>();
                newIps.add(priIp);
            }
            for (String newIp : newIps) {
                if (mappedIps.contains(newIp)) {
                    throw new InvalidParameterValueException("VM " + instanceId + " with " + newIp + " is already mapped to load balancer.");
                }
            }
        }
        List<String> vmIpsList = vmIdIpMap.get(instanceId);
        String vmLbIp = null;
        if (vmIpsList != null) {
            //check if the ips belongs to nic secondary ip
            for (String ip : vmIpsList) {
                // skip the primary ip from vm secondary ip comparisions
                if (ip.equals(priIp)) {
                    continue;
                }
                if (_nicSecondaryIpDao.findByIp4AddressAndNicId(ip, nicInSameNetwork.getId()) == null) {
                    throw new InvalidParameterValueException("VM ip " + ip + " specified does not belong to " + "nic in network " + nicInSameNetwork.getNetworkId());
                }
            }
        } else {
            vmIpsList = new ArrayList<String>();
            vmIpsList.add(priIp);
        }
        // assign for primary ip and ip passed in vmidipmap
        if (instanceIds != null) {
            if (instanceIds.contains(instanceId)) {
                vmIpsList.add(priIp);
            }
        }
        vmIdIpMap.put(instanceId, vmIpsList);
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Adding " + vm + " to the load balancer pool");
        }
        vmsToAdd.add(vm);
    }
    final Set<Long> vmIds = vmIdIpMap.keySet();
    final Map<Long, List<String>> newMap = vmIdIpMap;
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            for (Long vmId : vmIds) {
                final Set<String> lbVmIps = new HashSet<String>(newMap.get(vmId));
                for (String vmIp : lbVmIps) {
                    LoadBalancerVMMapVO map = new LoadBalancerVMMapVO(loadBalancer.getId(), vmId, vmIp, false);
                    map = _lb2VmMapDao.persist(map);
                }
            }
        }
    });
    if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancerId)) {
        // We can consider the job done.
        return true;
    }
    boolean success = false;
    FirewallRule.State backupState = loadBalancer.getState();
    try {
        loadBalancer.setState(FirewallRule.State.Add);
        _lbDao.persist(loadBalancer);
        applyLoadBalancerConfig(loadBalancerId);
        success = true;
    } catch (ResourceUnavailableException e) {
        s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
        success = false;
    } finally {
        if (!success) {
            final List<Long> vmInstanceIds = new ArrayList<Long>();
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    for (Long vmId : vmIds) {
                        vmInstanceIds.add(vmId);
                    }
                }
            });
            if (!vmInstanceIds.isEmpty()) {
                _lb2VmMapDao.remove(loadBalancer.getId(), vmInstanceIds, null);
                s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + "  while attaching VM: " + vmInstanceIds);
            }
            loadBalancer.setState(backupState);
            _lbDao.persist(loadBalancer);
            CloudRuntimeException ex = new CloudRuntimeException("Failed to add specified loadbalancerruleid for vms " + vmInstanceIds);
            ex.addProxyObject(loadBalancer.getUuid(), "loadBalancerId");
            // right VO object or table name.
            throw ex;
        }
    }
    return success;
}
Also used : Account(com.cloud.user.Account) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ArrayList(java.util.ArrayList) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) UserVm(com.cloud.uservm.UserVm) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) FirewallRule(com.cloud.network.rules.FirewallRule) HashSet(java.util.HashSet) Nic(com.cloud.vm.Nic) CallContext(org.apache.cloudstack.context.CallContext) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 47 with TransactionStatus

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

the class LoadBalancingRulesManagerImpl method applyLoadBalancerRules.

@DB
protected boolean applyLoadBalancerRules(List<LoadBalancerVO> lbs, boolean updateRulesInDB) throws ResourceUnavailableException {
    List<LoadBalancingRule> rules = new ArrayList<LoadBalancingRule>();
    for (LoadBalancerVO lb : lbs) {
        rules.add(getLoadBalancerRuleToApply(lb));
    }
    if (!applyLbRules(rules, false)) {
        s_logger.debug("LB rules are not completely applied");
        return false;
    }
    if (updateRulesInDB) {
        for (final LoadBalancerVO lb : lbs) {
            boolean checkForReleaseElasticIp = Transaction.execute(new TransactionCallback<Boolean>() {

                @Override
                public Boolean doInTransaction(TransactionStatus status) {
                    boolean checkForReleaseElasticIp = false;
                    if (lb.getState() == FirewallRule.State.Revoke) {
                        removeLBRule(lb);
                        s_logger.debug("LB " + lb.getId() + " is successfully removed");
                        checkForReleaseElasticIp = true;
                    } else if (lb.getState() == FirewallRule.State.Add) {
                        lb.setState(FirewallRule.State.Active);
                        s_logger.debug("LB rule " + lb.getId() + " state is set to Active");
                        _lbDao.persist(lb);
                    }
                    // remove LB-Vm mappings that were state to revoke
                    List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lb.getId(), true);
                    List<Long> instanceIds = new ArrayList<Long>();
                    for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) {
                        instanceIds.add(lbVmMap.getInstanceId());
                        _lb2VmMapDao.remove(lb.getId(), lbVmMap.getInstanceId(), lbVmMap.getInstanceIp(), null);
                        s_logger.debug("Load balancer rule id " + lb.getId() + " is removed for vm " + lbVmMap.getInstanceId() + " instance ip " + lbVmMap.getInstanceIp());
                    }
                    if (_lb2VmMapDao.listByLoadBalancerId(lb.getId()).isEmpty()) {
                        lb.setState(FirewallRule.State.Add);
                        _lbDao.persist(lb);
                        s_logger.debug("LB rule " + lb.getId() + " state is set to Add as there are no more active LB-VM mappings");
                    }
                    // remove LB-Stickiness policy mapping that were state to revoke
                    List<LBStickinessPolicyVO> stickinesspolicies = _lb2stickinesspoliciesDao.listByLoadBalancerId(lb.getId(), true);
                    if (!stickinesspolicies.isEmpty()) {
                        _lb2stickinesspoliciesDao.remove(lb.getId(), true);
                        s_logger.debug("Load balancer rule id " + lb.getId() + " is removed stickiness policies");
                    }
                    // remove LB-HealthCheck policy mapping that were state to
                    // revoke
                    List<LBHealthCheckPolicyVO> healthCheckpolicies = _lb2healthcheckDao.listByLoadBalancerId(lb.getId(), true);
                    if (!healthCheckpolicies.isEmpty()) {
                        _lb2healthcheckDao.remove(lb.getId(), true);
                        s_logger.debug("Load balancer rule id " + lb.getId() + " is removed health check monitors policies");
                    }
                    LoadBalancerCertMapVO lbCertMap = _lbCertMapDao.findByLbRuleId(lb.getId());
                    if (lbCertMap != null && lbCertMap.isRevoke()) {
                        _lbCertMapDao.remove(lbCertMap.getId());
                        s_logger.debug("Load balancer rule id " + lb.getId() + " removed certificate mapping");
                    }
                    return checkForReleaseElasticIp;
                }
            });
            if (checkForReleaseElasticIp && lb.getSourceIpAddressId() != null) {
                boolean success = true;
                long count = _firewallDao.countRulesByIpId(lb.getSourceIpAddressId());
                if (count == 0) {
                    try {
                        success = handleSystemLBIpRelease(lb);
                    } catch (Exception ex) {
                        s_logger.warn("Failed to release system ip as a part of lb rule " + lb + " deletion due to exception ", ex);
                        success = false;
                    } finally {
                        if (!success) {
                            s_logger.warn("Failed to release system ip as a part of lb rule " + lb + " deletion");
                        }
                    }
                }
            }
            // VPC, unassign it from the network
            if (lb.getSourceIpAddressId() != null) {
                IpAddress ip = _ipAddressDao.findById(lb.getSourceIpAddressId());
                _vpcMgr.unassignIPFromVpcNetwork(ip.getId(), lb.getNetworkId());
            }
        }
    }
    return true;
}
Also used : ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) LoadBalancerCertMapVO(com.cloud.network.dao.LoadBalancerCertMapVO) InvalidParameterException(java.security.InvalidParameterException) TransactionCallbackWithException(com.cloud.utils.db.TransactionCallbackWithException) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) ArrayList(java.util.ArrayList) List(java.util.List) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) IpAddress(com.cloud.network.IpAddress) DB(com.cloud.utils.db.DB)

Example 48 with TransactionStatus

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

the class LoadBalancingRulesManagerImpl method configureLbAutoScaleVmGroup.

@Override
@DB
public boolean configureLbAutoScaleVmGroup(final long vmGroupid, String currentState) throws ResourceUnavailableException {
    final AutoScaleVmGroupVO vmGroup = _autoScaleVmGroupDao.findById(vmGroupid);
    boolean success = false;
    final LoadBalancerVO loadBalancer = _lbDao.findById(vmGroup.getLoadBalancerId());
    FirewallRule.State backupState = loadBalancer.getState();
    if (vmGroup.getState().equals(AutoScaleVmGroup.State_New)) {
        loadBalancer.setState(FirewallRule.State.Add);
        _lbDao.persist(loadBalancer);
    } else if (loadBalancer.getState() == FirewallRule.State.Active && vmGroup.getState().equals(AutoScaleVmGroup.State_Revoke)) {
        loadBalancer.setState(FirewallRule.State.Add);
        _lbDao.persist(loadBalancer);
    }
    try {
        success = applyAutoScaleConfig(loadBalancer, vmGroup, currentState);
    } catch (ResourceUnavailableException e) {
        s_logger.warn("Unable to configure AutoScaleVmGroup to the lb rule: " + loadBalancer.getId() + " because resource is unavaliable:", e);
        if (isRollBackAllowedForProvider(loadBalancer)) {
            loadBalancer.setState(backupState);
            _lbDao.persist(loadBalancer);
            s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " lb state rolback while creating AutoscaleVmGroup");
        }
        throw e;
    } finally {
        if (!success) {
            s_logger.warn("Failed to configure LB Auto Scale Vm Group with Id:" + vmGroupid);
        }
    }
    if (success) {
        if (vmGroup.getState().equals(AutoScaleVmGroup.State_New)) {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    loadBalancer.setState(FirewallRule.State.Active);
                    s_logger.debug("LB rule " + loadBalancer.getId() + " state is set to Active");
                    _lbDao.persist(loadBalancer);
                    vmGroup.setState(AutoScaleVmGroup.State_Enabled);
                    _autoScaleVmGroupDao.persist(vmGroup);
                    s_logger.debug("LB Auto Scale Vm Group with Id: " + vmGroupid + " is set to Enabled state.");
                }
            });
        }
        s_logger.info("Successfully configured LB Autoscale Vm Group with Id: " + vmGroupid);
    }
    return success;
}
Also used : AutoScaleVmGroupVO(com.cloud.network.as.AutoScaleVmGroupVO) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) FirewallRule(com.cloud.network.rules.FirewallRule) DB(com.cloud.utils.db.DB)

Example 49 with TransactionStatus

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

the class PublicNetworkGuru method deallocate.

@Override
@DB
public void deallocate(Network network, NicProfile nic, VirtualMachineProfile vm) {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("public network deallocate network: networkId: " + nic.getNetworkId() + ", ip: " + nic.getIPv4Address());
    }
    final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(nic.getNetworkId(), nic.getIPv4Address());
    if (ip != null && nic.getReservationStrategy() != ReservationStrategy.Managed) {
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                _ipAddrMgr.markIpAsUnavailable(ip.getId());
                _ipAddressDao.unassignIpAddress(ip.getId());
            }
        });
    }
    nic.deallocate();
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Deallocated nic: " + nic);
    }
}
Also used : TransactionStatus(com.cloud.utils.db.TransactionStatus) IPAddressVO(com.cloud.network.dao.IPAddressVO) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) DB(com.cloud.utils.db.DB)

Example 50 with TransactionStatus

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

the class ManagementServerImpl method updateDomain.

@Override
@DB
public DomainVO updateDomain(final UpdateDomainCmd cmd) {
    final Long domainId = cmd.getId();
    final String domainName = cmd.getDomainName();
    final String networkDomain = cmd.getNetworkDomain();
    // check if domain exists in the system
    final DomainVO domain = _domainDao.findById(domainId);
    if (domain == null) {
        final InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find domain with specified domain id");
        ex.addProxyObject(domainId.toString(), "domainId");
        throw ex;
    } else if (domain.getParent() == null && domainName != null) {
        // name
        throw new InvalidParameterValueException("ROOT domain can not be edited with a new name");
    }
    final Account caller = getCaller();
    _accountMgr.checkAccess(caller, domain);
    // domain name is unique under the parent domain
    if (domainName != null) {
        final SearchCriteria<DomainVO> sc = _domainDao.createSearchCriteria();
        sc.addAnd("name", SearchCriteria.Op.EQ, domainName);
        sc.addAnd("parent", SearchCriteria.Op.EQ, domain.getParent());
        final List<DomainVO> domains = _domainDao.search(sc, null);
        final boolean sameDomain = domains.size() == 1 && domains.get(0).getId() == domainId;
        if (!domains.isEmpty() && !sameDomain) {
            final InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system");
            ex.addProxyObject(domain.getUuid(), "domainId");
            throw ex;
        }
    }
    // validate network domain
    if (networkDomain != null && !networkDomain.isEmpty()) {
        if (!NetUtils.verifyDomainName(networkDomain)) {
            throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\"");
        }
    }
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(final TransactionStatus status) {
            if (domainName != null) {
                final String updatedDomainPath = getUpdatedDomainPath(domain.getPath(), domainName);
                updateDomainChildren(domain, updatedDomainPath);
                domain.setName(domainName);
                domain.setPath(updatedDomainPath);
            }
            if (networkDomain != null) {
                if (networkDomain.isEmpty()) {
                    domain.setNetworkDomain(null);
                } else {
                    domain.setNetworkDomain(networkDomain);
                }
            }
            _domainDao.update(domainId, domain);
        }
    });
    return _domainDao.findById(domainId);
}
Also used : DomainVO(com.cloud.domain.DomainVO) Account(com.cloud.user.Account) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) DB(com.cloud.utils.db.DB)

Aggregations

TransactionStatus (com.cloud.utils.db.TransactionStatus)171 DB (com.cloud.utils.db.DB)139 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)100 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)93 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)77 ArrayList (java.util.ArrayList)54 Account (com.cloud.user.Account)44 List (java.util.List)44 ActionEvent (com.cloud.event.ActionEvent)40 ConfigurationException (javax.naming.ConfigurationException)40 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)35 IPAddressVO (com.cloud.network.dao.IPAddressVO)26 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)26 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)23 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)23 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)22 HashMap (java.util.HashMap)22 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)21 Network (com.cloud.network.Network)20 DataCenterVO (com.cloud.dc.DataCenterVO)17