Search in sources :

Example 11 with LoadBalancerCertMapVO

use of com.cloud.network.dao.LoadBalancerCertMapVO in project cosmic by MissionCriticalCloud.

the class LoadBalancingRulesManagerImpl method applyLoadBalancerRules.

@DB
protected boolean applyLoadBalancerRules(final List<LoadBalancerVO> lbs, final boolean updateRulesInDB) throws ResourceUnavailableException {
    final List<LoadBalancingRule> rules = new ArrayList<>();
    for (final 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) {
            final boolean checkForReleaseElasticIp = Transaction.execute(new TransactionCallback<Boolean>() {

                @Override
                public Boolean doInTransaction(final 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
                    final List<LoadBalancerVMMapVO> lbVmMaps = _lb2VmMapDao.listByLoadBalancerId(lb.getId(), true);
                    final List<Long> instanceIds = new ArrayList<>();
                    for (final 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
                    final 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
                    final 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");
                    }
                    final 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;
                final long count = _firewallDao.countRulesByIpId(lb.getSourceIpAddressId());
                if (count == 0) {
                    try {
                        success = handleSystemLBIpRelease(lb);
                    } catch (final 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) {
                final 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.utils.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 12 with LoadBalancerCertMapVO

use of com.cloud.network.dao.LoadBalancerCertMapVO in project cosmic by MissionCriticalCloud.

the class CertServiceTest method runDeleteSslCertBoundCert.

@Test
public void runDeleteSslCertBoundCert() throws NoSuchFieldException, IllegalAccessException {
    final TransactionLegacy txn = TransactionLegacy.open("runDeleteSslCertBoundCert");
    final CertServiceImpl certService = new CertServiceImpl();
    // setting mock objects
    final long certId = 1;
    certService._accountMgr = Mockito.mock(AccountManager.class);
    final Account account = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
    when(certService._accountMgr.getAccount(anyLong())).thenReturn(account);
    certService._domainDao = Mockito.mock(DomainDao.class);
    final DomainVO domain = new DomainVO("networkdomain", 1L, 1L, "networkdomain");
    when(certService._domainDao.findByIdIncludingRemoved(anyLong())).thenReturn(domain);
    certService._sslCertDao = Mockito.mock(SslCertDao.class);
    when(certService._sslCertDao.remove(anyLong())).thenReturn(true);
    when(certService._sslCertDao.findById(anyLong())).thenReturn(new SslCertVO());
    // rule holding the cert
    certService._lbCertDao = Mockito.mock(LoadBalancerCertMapDao.class);
    final List<LoadBalancerCertMapVO> lbMapList = new ArrayList<>();
    lbMapList.add(new LoadBalancerCertMapVO());
    certService._lbCertDao = Mockito.mock(LoadBalancerCertMapDao.class);
    when(certService._lbCertDao.listByCertId(anyLong())).thenReturn(lbMapList);
    certService._entityMgr = Mockito.mock(EntityManager.class);
    when(certService._entityMgr.findById(eq(LoadBalancerVO.class), anyLong())).thenReturn(new LoadBalancerVO());
    // creating the command
    final DeleteSslCertCmd deleteCmd = new DeleteSslCertCmdExtn();
    final Class<?> _class = deleteCmd.getClass().getSuperclass();
    final Field certField = _class.getDeclaredField("id");
    certField.setAccessible(true);
    certField.set(deleteCmd, certId);
    try {
        certService.deleteSslCert(deleteCmd);
        fail("Delete with a cert id bound to a lb should fail");
    } catch (final Exception e) {
        assertTrue(e.getMessage().contains("Certificate in use by a loadbalancer"));
    }
}
Also used : Account(com.cloud.user.Account) SslCertDao(com.cloud.network.dao.SslCertDao) LoadBalancerCertMapDao(com.cloud.network.dao.LoadBalancerCertMapDao) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LoadBalancerCertMapVO(com.cloud.network.dao.LoadBalancerCertMapVO) AccountVO(com.cloud.user.AccountVO) IOException(java.io.IOException) TransactionLegacy(com.cloud.utils.db.TransactionLegacy) DomainVO(com.cloud.domain.DomainVO) Field(java.lang.reflect.Field) EntityManager(com.cloud.dao.EntityManager) SslCertVO(com.cloud.network.dao.SslCertVO) DomainDao(com.cloud.domain.dao.DomainDao) AccountManager(com.cloud.user.AccountManager) DeleteSslCertCmd(com.cloud.api.command.user.loadbalancer.DeleteSslCertCmd) Test(org.junit.Test)

Example 13 with LoadBalancerCertMapVO

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

the class CertServiceTest method runDeleteSslCertBoundCert.

@Test
public void runDeleteSslCertBoundCert() throws NoSuchFieldException, IllegalAccessException {
    TransactionLegacy.open("runDeleteSslCertBoundCert");
    final CertServiceImpl certService = new CertServiceImpl();
    // setting mock objects
    final long certId = 1;
    certService._accountMgr = Mockito.mock(AccountManager.class);
    final Account account = new AccountVO("testaccount", 1, "networkdomain", (short) 0, UUID.randomUUID().toString());
    when(certService._accountMgr.getAccount(anyLong())).thenReturn(account);
    certService._domainDao = Mockito.mock(DomainDao.class);
    final DomainVO domain = new DomainVO("networkdomain", 1L, 1L, "networkdomain");
    when(certService._domainDao.findByIdIncludingRemoved(anyLong())).thenReturn(domain);
    certService._sslCertDao = Mockito.mock(SslCertDao.class);
    when(certService._sslCertDao.remove(anyLong())).thenReturn(true);
    when(certService._sslCertDao.findById(anyLong())).thenReturn(new SslCertVO());
    // rule holding the cert
    certService._lbCertDao = Mockito.mock(LoadBalancerCertMapDao.class);
    final List<LoadBalancerCertMapVO> lbMapList = new ArrayList<>();
    lbMapList.add(new LoadBalancerCertMapVO());
    certService._lbCertDao = Mockito.mock(LoadBalancerCertMapDao.class);
    when(certService._lbCertDao.listByCertId(anyLong())).thenReturn(lbMapList);
    certService._entityMgr = Mockito.mock(EntityManager.class);
    when(certService._entityMgr.findById(eq(LoadBalancerVO.class), nullable(Long.class))).thenReturn(new LoadBalancerVO());
    // creating the command
    final DeleteSslCertCmd deleteCmd = new DeleteSslCertCmdExtn();
    final Class<?> klazz = deleteCmd.getClass().getSuperclass();
    final Field certField = klazz.getDeclaredField("id");
    certField.setAccessible(true);
    certField.set(deleteCmd, certId);
    try {
        certService.deleteSslCert(deleteCmd);
        Assert.fail("Delete with a cert id bound to a lb should fail");
    } catch (final Exception e) {
        Assert.assertTrue(e.getMessage().contains("Certificate in use by a loadbalancer"));
    }
}
Also used : Account(com.cloud.user.Account) SslCertDao(com.cloud.network.dao.SslCertDao) LoadBalancerCertMapDao(com.cloud.network.dao.LoadBalancerCertMapDao) ArrayList(java.util.ArrayList) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) LoadBalancerCertMapVO(com.cloud.network.dao.LoadBalancerCertMapVO) AccountVO(com.cloud.user.AccountVO) IOException(java.io.IOException) DomainVO(com.cloud.domain.DomainVO) Field(java.lang.reflect.Field) EntityManager(com.cloud.utils.db.EntityManager) SslCertVO(com.cloud.network.dao.SslCertVO) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) DomainDao(com.cloud.domain.dao.DomainDao) AccountManager(com.cloud.user.AccountManager) DeleteSslCertCmd(org.apache.cloudstack.api.command.user.loadbalancer.DeleteSslCertCmd) Test(org.junit.Test)

Example 14 with LoadBalancerCertMapVO

use of com.cloud.network.dao.LoadBalancerCertMapVO 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) LoadBalancerVMMapVO(com.cloud.network.dao.LoadBalancerVMMapVO) ArrayList(java.util.ArrayList) List(java.util.List) FirewallRule(com.cloud.network.rules.FirewallRule) DB(com.cloud.utils.db.DB)

Example 15 with LoadBalancerCertMapVO

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

the class LoadBalancingRulesManagerImpl method assignCertToLoadBalancer.

@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_LB_CERT_ASSIGN, eventDescription = "assigning certificate to load balancer", async = true)
public boolean assignCertToLoadBalancer(long lbRuleId, Long certId) {
    CallContext caller = CallContext.current();
    LoadBalancerVO loadBalancer = _lbDao.findById(Long.valueOf(lbRuleId));
    if (loadBalancer == null) {
        throw new InvalidParameterException("Invalid load balancer id: " + lbRuleId);
    }
    SslCertVO certVO = _entityMgr.findById(SslCertVO.class, certId);
    if (certVO == null) {
        throw new InvalidParameterException("Invalid certificate id: " + certId);
    }
    _accountMgr.checkAccess(caller.getCallingAccount(), null, true, loadBalancer);
    // check if LB and Cert belong to the same account
    if (loadBalancer.getAccountId() != certVO.getAccountId()) {
        throw new InvalidParameterValueException("Access denied for account " + certVO.getAccountId());
    }
    String capability = getLBCapability(loadBalancer.getNetworkId(), Capability.SslTermination.getName());
    if (capability == null) {
        throw new InvalidParameterValueException("Ssl termination not supported by the loadbalancer");
    }
    // check if the lb is already bound
    LoadBalancerCertMapVO certMapRule = _lbCertMapDao.findByLbRuleId(loadBalancer.getId());
    if (certMapRule != null)
        throw new InvalidParameterValueException("Another certificate is already bound to the LB");
    // check for correct port
    if (loadBalancer.getLbProtocol() == null || !(loadBalancer.getLbProtocol().equals(NetUtils.SSL_PROTO)))
        throw new InvalidParameterValueException("Bad LB protocol: Expected ssl got " + loadBalancer.getLbProtocol());
    boolean success = false;
    FirewallRule.State backupState = loadBalancer.getState();
    try {
        loadBalancer.setState(FirewallRule.State.Add);
        _lbDao.persist(loadBalancer);
        LoadBalancerCertMapVO certMap = new LoadBalancerCertMapVO(lbRuleId, certId, false);
        _lbCertMapDao.persist(certMap);
        applyLoadBalancerConfig(loadBalancer.getId());
        success = true;
    } catch (ResourceUnavailableException e) {
        if (isRollBackAllowedForProvider(loadBalancer)) {
            loadBalancer.setState(backupState);
            _lbDao.persist(loadBalancer);
            LoadBalancerCertMapVO certMap = _lbCertMapDao.findByLbRuleId(lbRuleId);
            _lbCertMapDao.remove(certMap.getId());
            s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " while adding cert");
        }
        s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e);
    }
    return success;
}
Also used : InvalidParameterException(java.security.InvalidParameterException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) LoadBalancerVO(com.cloud.network.dao.LoadBalancerVO) SslCertVO(com.cloud.network.dao.SslCertVO) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) LoadBalancerCertMapVO(com.cloud.network.dao.LoadBalancerCertMapVO) CallContext(org.apache.cloudstack.context.CallContext) FirewallRule(com.cloud.network.rules.FirewallRule) ActionEvent(com.cloud.event.ActionEvent) DB(com.cloud.utils.db.DB)

Aggregations

LoadBalancerCertMapVO (com.cloud.network.dao.LoadBalancerCertMapVO)18 LoadBalancerVO (com.cloud.network.dao.LoadBalancerVO)12 SslCertVO (com.cloud.network.dao.SslCertVO)10 DB (com.cloud.utils.db.DB)10 ArrayList (java.util.ArrayList)10 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)8 Account (com.cloud.user.Account)8 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)8 ActionEvent (com.cloud.event.ActionEvent)6 FirewallRule (com.cloud.network.rules.FirewallRule)6 InvalidParameterException (java.security.InvalidParameterException)6 CallContext (com.cloud.context.CallContext)4 DomainVO (com.cloud.domain.DomainVO)4 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)4 LoadBalancerVMMapVO (com.cloud.network.dao.LoadBalancerVMMapVO)4 LoadBalancer (com.cloud.network.rules.LoadBalancer)4 Project (com.cloud.projects.Project)4 TransactionStatus (com.cloud.utils.db.TransactionStatus)4 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)4 List (java.util.List)4