Search in sources :

Example 11 with LoadBalancerVMMapVO

use of com.cloud.network.dao.LoadBalancerVMMapVO in project cloudstack by apache.

the class LoadBalancingRulesManagerImpl method removeVmFromLoadBalancers.

@Override
public boolean removeVmFromLoadBalancers(long instanceId) {
    boolean success = true;
    List<LoadBalancerVMMapVO> maps = _lb2VmMapDao.listByInstanceId(instanceId);
    if (maps == null || maps.isEmpty()) {
        return true;
    }
    Map<Long, List<Long>> lbsToReconfigure = new HashMap<Long, List<Long>>();
    // first set all existing lb mappings with Revoke state
    for (LoadBalancerVMMapVO map : maps) {
        long lbId = map.getLoadBalancerId();
        List<Long> instances = lbsToReconfigure.get(lbId);
        if (instances == null) {
            instances = new ArrayList<Long>();
        }
        instances.add(map.getInstanceId());
        lbsToReconfigure.put(lbId, instances);
        map.setRevoke(true);
        _lb2VmMapDao.persist(map);
        s_logger.debug("Set load balancer rule for revoke: rule id " + map.getLoadBalancerId() + ", vmId " + instanceId);
    }
    // Reapply all lbs that had the vm assigned
    if (lbsToReconfigure != null) {
        for (Map.Entry<Long, List<Long>> lb : lbsToReconfigure.entrySet()) {
            if (!removeFromLoadBalancerInternal(lb.getKey(), lb.getValue(), false, new HashMap<Long, List<String>>())) {
                success = false;
            }
        }
    }
    return success;
}
Also used : HashMap(java.util.HashMap) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) HashMap(java.util.HashMap)

Example 12 with LoadBalancerVMMapVO

use of com.cloud.network.dao.LoadBalancerVMMapVO in project cloudstack by apache.

the class LoadBalancingRulesManagerImpl method deleteLoadBalancerRule.

@DB
public boolean deleteLoadBalancerRule(final long loadBalancerId, boolean apply, Account caller, long callerUserId, boolean rollBack) {
    final LoadBalancerVO lb = _lbDao.findById(loadBalancerId);
    FirewallRule.State backupState = lb.getState();
    // remove any ssl certs associated with this LB rule before trying to delete it.
    LoadBalancerCertMapVO lbCertMap = _lbCertMapDao.findByLbRuleId(loadBalancerId);
    if (lbCertMap != null) {
        boolean removeResult = removeCertFromLoadBalancer(loadBalancerId);
        if (!removeResult) {
            throw new CloudRuntimeException("Unable to remove certificate from load balancer rule " + loadBalancerId);
        }
    }
    List<LoadBalancerVMMapVO> backupMaps = Transaction.execute(new TransactionCallback<List<LoadBalancerVMMapVO>>() {

        @Override
        public List<LoadBalancerVMMapVO> doInTransaction(TransactionStatus status) {
            boolean generateUsageEvent = false;
            if (lb.getState() == FirewallRule.State.Staged) {
                if (s_logger.isDebugEnabled()) {
                    s_logger.debug("Found a rule that is still in stage state so just removing it: " + lb);
                }
                generateUsageEvent = true;
            } else if (lb.getState() == FirewallRule.State.Add || lb.getState() == FirewallRule.State.Active) {
                lb.setState(FirewallRule.State.Revoke);
                _lbDao.persist(lb);
                generateUsageEvent = true;
            }
            List<LoadBalancerVMMapVO> backupMaps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
            List<LoadBalancerVMMapVO> maps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
            if (maps != null) {
                for (LoadBalancerVMMapVO map : maps) {
                    map.setRevoke(true);
                    _lb2VmMapDao.persist(map);
                    s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", vmId " + map.getInstanceId());
                }
            }
            List<LBHealthCheckPolicyVO> hcPolicies = _lb2healthcheckDao.listByLoadBalancerIdAndDisplayFlag(loadBalancerId, null);
            for (LBHealthCheckPolicyVO lbHealthCheck : hcPolicies) {
                lbHealthCheck.setRevoke(true);
                _lb2healthcheckDao.persist(lbHealthCheck);
            }
            if (generateUsageEvent) {
                // Generate usage event right after all rules were marked for revoke
                Network network = _networkModel.getNetwork(lb.getNetworkId());
                UsageEventUtils.publishUsageEvent(EventTypes.EVENT_LOAD_BALANCER_DELETE, lb.getAccountId(), network.getDataCenterId(), lb.getId(), null, LoadBalancingRule.class.getName(), lb.getUuid());
            }
            return backupMaps;
        }
    });
    // gather external network usage stats for this lb rule
    NetworkVO network = _networkDao.findById(lb.getNetworkId());
    if (network != null) {
        if (_networkModel.networkIsConfiguredForExternalNetworking(network.getDataCenterId(), network.getId())) {
            _externalDeviceUsageMgr.updateExternalLoadBalancerNetworkUsageStats(loadBalancerId);
        }
    }
    if (apply) {
        try {
            if (!applyLoadBalancerConfig(loadBalancerId)) {
                s_logger.warn("Unable to apply the load balancer config");
                return false;
            }
        } catch (ResourceUnavailableException e) {
            if (rollBack && isRollBackAllowedForProvider(lb)) {
                if (backupMaps != null) {
                    for (LoadBalancerVMMapVO map : backupMaps) {
                        _lb2VmMapDao.persist(map);
                        s_logger.debug("LB Rollback rule id: " + loadBalancerId + ", vmId " + map.getInstanceId());
                    }
                }
                lb.setState(backupState);
                _lbDao.persist(lb);
                s_logger.debug("LB Rollback rule id: " + loadBalancerId + " while deleting LB rule.");
            } else {
                s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
            }
            return false;
        }
    }
    FirewallRuleVO relatedRule = _firewallDao.findByRelatedId(lb.getId());
    if (relatedRule != null) {
        s_logger.warn("Unable to remove firewall rule id=" + lb.getId() + " as it has related firewall rule id=" + relatedRule.getId() + "; leaving it in Revoke state");
        return false;
    } else {
        _firewallMgr.removeRule(lb);
    }
    // FIXME: breaking the dependency on ELB manager. This breaks
    // functionality of ELB using virtual router
    // Bug CS-15411 opened to document this
    // _elbMgr.handleDeleteLoadBalancerRule(lb, callerUserId, caller);
    s_logger.debug("Load balancer with id " + lb.getId() + " is removed successfully");
    return true;
}
Also used : NetworkVO(com.cloud.network.dao.NetworkVO) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LoadBalancerCertMapVO(com.cloud.network.dao.LoadBalancerCertMapVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) LBHealthCheckPolicyVO(com.cloud.network.LBHealthCheckPolicyVO) FirewallRuleVO(com.cloud.network.rules.FirewallRuleVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Network(com.cloud.network.Network) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) ArrayList(java.util.ArrayList) List(java.util.List) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) FirewallRule(com.cloud.network.rules.FirewallRule) DB(com.cloud.utils.db.DB)

Example 13 with LoadBalancerVMMapVO

use of com.cloud.network.dao.LoadBalancerVMMapVO in project cloudstack by apache.

the class LoadBalancingRulesManagerImpl method deleteLBHealthCheckPolicy.

@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_LB_HEALTHCHECKPOLICY_DELETE, eventDescription = "revoking LB HealthCheck policy ", async = true)
public boolean deleteLBHealthCheckPolicy(long healthCheckPolicyId, boolean apply) {
    boolean success = true;
    CallContext caller = CallContext.current();
    LBHealthCheckPolicyVO healthCheckPolicy = _lb2healthcheckDao.findById(healthCheckPolicyId);
    if (healthCheckPolicy == null) {
        throw new InvalidParameterException("Invalid HealthCheck policy id value: " + healthCheckPolicyId);
    }
    LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(healthCheckPolicy.getLoadBalancerId()));
    if (loadBalancer == null) {
        throw new InvalidParameterException("Invalid Load balancer : " + healthCheckPolicy.getLoadBalancerId() + " for HealthCheck policy id: " + healthCheckPolicyId);
    }
    final long loadBalancerId = loadBalancer.getId();
    FirewallRule.State backupState = loadBalancer.getState();
    _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer);
    if (apply) {
        if (loadBalancer.getState() == FirewallRule.State.Active) {
            loadBalancer.setState(FirewallRule.State.Add);
            _lbDao.persist(loadBalancer);
        }
        boolean backupStickyState = healthCheckPolicy.isRevoke();
        healthCheckPolicy.setRevoke(true);
        _lb2healthcheckDao.persist(healthCheckPolicy);
        s_logger.debug("Set health check policy to revoke for loadbalancing rule id : " + loadBalancerId + ", healthCheckpolicyID " + healthCheckPolicyId);
        // removing the state of services set by the monitor.
        final List<LoadBalancerVMMapVO> maps = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
        if (maps != null) {
            Transaction.execute(new TransactionCallbackNoReturn() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    s_logger.debug("Resetting health state policy for services in loadbalancing rule id : " + loadBalancerId);
                    for (LoadBalancerVMMapVO map : maps) {
                        map.setState(null);
                        _lb2VmMapDao.persist(map);
                    }
                }
            });
        }
        try {
            if (!applyLoadBalancerConfig(loadBalancerId)) {
                s_logger.warn("Failed to remove load balancer rule id " + loadBalancerId + " for healthCheckpolicyID " + healthCheckPolicyId);
                throw new CloudRuntimeException("Failed to remove load balancer rule id " + loadBalancerId + " for healthCheckpolicyID " + healthCheckPolicyId);
            }
        } catch (ResourceUnavailableException e) {
            if (isRollBackAllowedForProvider(loadBalancer)) {
                healthCheckPolicy.setRevoke(backupStickyState);
                _lb2healthcheckDao.persist(healthCheckPolicy);
                loadBalancer.setState(backupState);
                _lbDao.persist(loadBalancer);
                s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + "  while deleting healthcheck policy: " + healthCheckPolicyId);
            }
            s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
            success = false;
        }
    } else {
        _lb2healthcheckDao.remove(healthCheckPolicy.getLoadBalancerId());
    }
    return success;
}
Also used : LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) LBHealthCheckPolicyVO(com.cloud.network.LBHealthCheckPolicyVO) CallContext(org.apache.cloudstack.context.CallContext) InvalidParameterException(java.security.InvalidParameterException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) FirewallRule(com.cloud.network.rules.FirewallRule) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Example 14 with LoadBalancerVMMapVO

use of com.cloud.network.dao.LoadBalancerVMMapVO in project cloudstack by apache.

the class LoadBalancingRulesManagerImpl method listLoadBalancerInstances.

@Override
public Pair<List<? extends UserVm>, List<String>> listLoadBalancerInstances(ListLoadBalancerRuleInstancesCmd cmd) throws PermissionDeniedException {
    Account caller = CallContext.current().getCallingAccount();
    Long loadBalancerId = cmd.getId();
    Boolean applied = cmd.isApplied();
    if (applied == null) {
        applied = Boolean.TRUE;
    }
    LoadBalancerVO loadBalancer = _lbDao.findById(loadBalancerId);
    if (loadBalancer == null) {
        return null;
    }
    _accountMgr.checkAccess(caller, null, true, loadBalancer);
    List<UserVmVO> loadBalancerInstances = new ArrayList<UserVmVO>();
    List<String> serviceStates = new ArrayList<String>();
    List<LoadBalancerVMMapVO> vmLoadBalancerMappings = null;
    vmLoadBalancerMappings = _lb2VmMapDao.listByLoadBalancerId(loadBalancerId);
    if (vmLoadBalancerMappings == null) {
        String msg = "no VM Loadbalancer Mapping found";
        s_logger.error(msg);
        throw new CloudRuntimeException(msg);
    }
    Map<Long, String> vmServiceState = new HashMap<Long, String>(vmLoadBalancerMappings.size());
    List<Long> appliedInstanceIdList = new ArrayList<Long>();
    if ((vmLoadBalancerMappings != null) && !vmLoadBalancerMappings.isEmpty()) {
        for (LoadBalancerVMMapVO vmLoadBalancerMapping : vmLoadBalancerMappings) {
            appliedInstanceIdList.add(vmLoadBalancerMapping.getInstanceId());
            vmServiceState.put(vmLoadBalancerMapping.getInstanceId(), vmLoadBalancerMapping.getState());
        }
    }
    List<UserVmVO> userVms = _vmDao.listVirtualNetworkInstancesByAcctAndNetwork(loadBalancer.getAccountId(), loadBalancer.getNetworkId());
    for (UserVmVO userVm : userVms) {
        // an unknown state, skip it
        switch(userVm.getState()) {
            case Destroyed:
            case Expunging:
            case Error:
            case Unknown:
                continue;
        }
        boolean isApplied = appliedInstanceIdList.contains(userVm.getId());
        if ((isApplied && applied) || (!isApplied && !applied)) {
            loadBalancerInstances.add(userVm);
            serviceStates.add(vmServiceState.get(userVm.getId()));
        }
    }
    return new Pair<List<? extends UserVm>, List<String>>(loadBalancerInstances, serviceStates);
}
Also used : Account(com.cloud.user.Account) UserVmVO(com.cloud.vm.UserVmVO) HashMap(java.util.HashMap) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) ArrayList(java.util.ArrayList) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) Pair(com.cloud.utils.Pair)

Example 15 with LoadBalancerVMMapVO

use of com.cloud.network.dao.LoadBalancerVMMapVO in project cloudstack by apache.

the class LoadBalancingRulesManagerImpl method getLbInstances.

@Override
public Map<Ip, UserVm> getLbInstances(long lbId) {
    Map<Ip, UserVm> dstList = new HashMap<Ip, UserVm>();
    List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lbId);
    LoadBalancerVO lb = _lbDao.findById(lbId);
    for (LoadBalancerVMMapVO lbVmMap : lbVmMaps) {
        UserVm vm = _vmDao.findById(lbVmMap.getInstanceId());
        Nic nic = _nicDao.findByInstanceIdAndNetworkIdIncludingRemoved(lb.getNetworkId(), vm.getId());
        Ip ip = new Ip(nic.getIPv4Address());
        dstList.put(ip, vm);
    }
    return dstList;
}
Also used : UserVm(com.cloud.uservm.UserVm) HashMap(java.util.HashMap) Ip(com.cloud.utils.net.Ip) PublicIp(com.cloud.network.addr.PublicIp) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) Nic(com.cloud.vm.Nic) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO)

Aggregations

LoadBalancerVMMapVO (com.cloud.network.dao.LoadBalancerVMMapVO)17 ArrayList (java.util.ArrayList)15 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)11 List (java.util.List)10 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)7 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)6 DB (com.cloud.utils.db.DB)6 TransactionStatus (com.cloud.utils.db.TransactionStatus)5 HashMap (java.util.HashMap)5 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)4 FirewallRule (com.cloud.network.rules.FirewallRule)4 Account (com.cloud.user.Account)4 ActionEvent (com.cloud.event.ActionEvent)3 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)3 Network (com.cloud.network.Network)3 NetworkVO (com.cloud.network.dao.NetworkVO)3 UserVm (com.cloud.uservm.UserVm)3 Pair (com.cloud.utils.Pair)3 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)3 Nic (com.cloud.vm.Nic)3