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;
}
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"));
}
}
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"));
}
}
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;
}
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;
}
Aggregations