use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class DhcpSubNetRules method accept.
@Override
public boolean accept(final NetworkTopologyVisitor visitor, final VirtualRouter router) throws ResourceUnavailableException {
_router = router;
UserVmDao userVmDao = visitor.getVirtualNetworkApplianceFactory().getUserVmDao();
final UserVmVO vm = userVmDao.findById(_profile.getId());
userVmDao.loadDetails(vm);
NicDao nicDao = visitor.getVirtualNetworkApplianceFactory().getNicDao();
// check if this is not the primary subnet.
final NicVO domrGuestNic = nicDao.findByInstanceIdAndIpAddressAndVmtype(_router.getId(), nicDao.getIpAddress(_nic.getNetworkId(), _router.getId()), VirtualMachine.Type.DomainRouter);
// networks.
if (!NetUtils.sameSubnet(domrGuestNic.getIPv4Address(), _nic.getIPv4Address(), _nic.getIPv4Netmask())) {
final NicIpAliasDao nicIpAliasDao = visitor.getVirtualNetworkApplianceFactory().getNicIpAliasDao();
final List<NicIpAliasVO> aliasIps = nicIpAliasDao.listByNetworkIdAndState(domrGuestNic.getNetworkId(), NicIpAlias.State.active);
boolean ipInVmsubnet = false;
for (final NicIpAliasVO alias : aliasIps) {
// check if any of the alias ips belongs to the Vm's subnet.
if (NetUtils.sameSubnet(alias.getIp4Address(), _nic.getIPv4Address(), _nic.getIPv4Netmask())) {
ipInVmsubnet = true;
break;
}
}
PublicIp routerPublicIP = null;
DataCenterDao dcDao = visitor.getVirtualNetworkApplianceFactory().getDcDao();
final DataCenter dc = dcDao.findById(_router.getDataCenterId());
if (ipInVmsubnet == false) {
try {
if (_network.getTrafficType() == TrafficType.Guest && _network.getGuestType() == GuestType.Shared) {
HostPodDao podDao = visitor.getVirtualNetworkApplianceFactory().getPodDao();
podDao.findById(vm.getPodIdToDeployIn());
final Account caller = CallContext.current().getCallingAccount();
VlanDao vlanDao = visitor.getVirtualNetworkApplianceFactory().getVlanDao();
final List<VlanVO> vlanList = vlanDao.listVlansByNetworkIdAndGateway(_network.getId(), _nic.getIPv4Gateway());
final List<Long> vlanDbIdList = new ArrayList<Long>();
for (final VlanVO vlan : vlanList) {
vlanDbIdList.add(vlan.getId());
}
IpAddressManager ipAddrMgr = visitor.getVirtualNetworkApplianceFactory().getIpAddrMgr();
if (dc.getNetworkType() == NetworkType.Basic) {
routerPublicIP = ipAddrMgr.assignPublicIpAddressFromVlans(_router.getDataCenterId(), vm.getPodIdToDeployIn(), caller, Vlan.VlanType.DirectAttached, vlanDbIdList, _nic.getNetworkId(), null, _nic.getIPv4Gateway(), false);
} else {
routerPublicIP = ipAddrMgr.assignPublicIpAddressFromVlans(_router.getDataCenterId(), null, caller, Vlan.VlanType.DirectAttached, vlanDbIdList, _nic.getNetworkId(), null, _nic.getIPv4Gateway(), false);
}
_routerAliasIp = routerPublicIP.getAddress().addr();
}
} catch (final InsufficientAddressCapacityException e) {
s_logger.info(e.getMessage());
s_logger.info("unable to configure dhcp for this VM.");
return false;
}
// this means we did not create an IP alias on the router.
_nicAlias = new NicIpAliasVO(domrGuestNic.getId(), _routerAliasIp, _router.getId(), CallContext.current().getCallingAccountId(), _network.getDomainId(), _nic.getNetworkId(), _nic.getIPv4Gateway(), _nic.getIPv4Netmask());
_nicAlias.setAliasCount(routerPublicIP.getIpMacAddress());
nicIpAliasDao.persist(_nicAlias);
final boolean result = visitor.visit(this);
if (result == false) {
final NicIpAliasVO ipAliasVO = nicIpAliasDao.findByInstanceIdAndNetworkId(_network.getId(), _router.getId());
final PublicIp routerPublicIPFinal = routerPublicIP;
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
nicIpAliasDao.expunge(ipAliasVO.getId());
IPAddressDao ipAddressDao = visitor.getVirtualNetworkApplianceFactory().getIpAddressDao();
ipAddressDao.unassignIpAddress(routerPublicIPFinal.getId());
}
});
throw new CloudRuntimeException("failed to configure ip alias on the router as a part of dhcp config");
}
}
return true;
}
return true;
}
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);
}
}
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;
}
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;
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class LoadBalancingRulesManagerImpl method createPublicLoadBalancer.
@DB
@Override
public LoadBalancer createPublicLoadBalancer(final String xId, final String name, final String description, final int srcPort, final int destPort, final long sourceIpId, final String protocol, final String algorithm, final boolean openFirewall, final CallContext caller, final String lbProtocol, final Boolean forDisplay) throws NetworkRuleConflictException {
if (!NetUtils.isValidPort(destPort)) {
throw new InvalidParameterValueException("privatePort is an invalid value: " + destPort);
}
if ((algorithm == null) || !NetUtils.isValidAlgorithm(algorithm)) {
throw new InvalidParameterValueException("Invalid algorithm: " + algorithm);
}
final IPAddressVO ipAddr = _ipAddressDao.findById(sourceIpId);
// make sure ip address exists
if (ipAddr == null || !ipAddr.readyToUse()) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id specified");
if (ipAddr == null) {
ex.addProxyObject(String.valueOf(sourceIpId), "sourceIpId");
} else {
ex.addProxyObject(ipAddr.getUuid(), "sourceIpId");
}
throw ex;
} else if (ipAddr.isOneToOneNat()) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to create load balancer rule; specified sourceip id has static nat enabled");
ex.addProxyObject(ipAddr.getUuid(), "sourceIpId");
throw ex;
}
_accountMgr.checkAccess(caller.getCallingAccount(), null, true, ipAddr);
final Long networkId = ipAddr.getAssociatedWithNetworkId();
if (networkId == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to create load balancer rule ; specified sourceip id is not associated with any network");
ex.addProxyObject(ipAddr.getUuid(), "sourceIpId");
throw ex;
}
// verify that lb service is supported by the network
isLbServiceSupportedInNetwork(networkId, Scheme.Public);
_firewallMgr.validateFirewallRule(caller.getCallingAccount(), ipAddr, srcPort, srcPort, protocol, Purpose.LoadBalancing, FirewallRuleType.User, networkId, null);
LoadBalancerVO newRule = new LoadBalancerVO(xId, name, description, sourceIpId, srcPort, destPort, algorithm, networkId, ipAddr.getAllocatedToAccountId(), ipAddr.getAllocatedInDomainId(), lbProtocol);
// verify rule is supported by Lb provider of the network
Ip sourceIp = getSourceIp(newRule);
LoadBalancingRule loadBalancing = new LoadBalancingRule(newRule, new ArrayList<LbDestination>(), new ArrayList<LbStickinessPolicy>(), new ArrayList<LbHealthCheckPolicy>(), sourceIp, null, lbProtocol);
if (!validateLbRule(loadBalancing)) {
throw new InvalidParameterValueException("LB service provider cannot support this rule");
}
return Transaction.execute(new TransactionCallbackWithException<LoadBalancerVO, NetworkRuleConflictException>() {
@Override
public LoadBalancerVO doInTransaction(TransactionStatus status) throws NetworkRuleConflictException {
LoadBalancerVO newRule = new LoadBalancerVO(xId, name, description, sourceIpId, srcPort, destPort, algorithm, networkId, ipAddr.getAllocatedToAccountId(), ipAddr.getAllocatedInDomainId(), lbProtocol);
if (forDisplay != null) {
newRule.setDisplay(forDisplay);
}
// verify rule is supported by Lb provider of the network
Ip sourceIp = getSourceIp(newRule);
LoadBalancingRule loadBalancing = new LoadBalancingRule(newRule, new ArrayList<LbDestination>(), new ArrayList<LbStickinessPolicy>(), new ArrayList<LbHealthCheckPolicy>(), sourceIp, null, lbProtocol);
if (!validateLbRule(loadBalancing)) {
throw new InvalidParameterValueException("LB service provider cannot support this rule");
}
newRule = _lbDao.persist(newRule);
// create rule for all CIDRs
if (openFirewall) {
_firewallMgr.createRuleForAllCidrs(sourceIpId, caller.getCallingAccount(), srcPort, srcPort, protocol, null, null, newRule.getId(), networkId);
}
boolean success = true;
try {
_firewallMgr.detectRulesConflict(newRule);
if (!_firewallDao.setStateToAdd(newRule)) {
throw new CloudRuntimeException("Unable to update the state to add for " + newRule);
}
s_logger.debug("Load balancer " + newRule.getId() + " for Ip address id=" + sourceIpId + ", public port " + srcPort + ", private port " + destPort + " is added successfully.");
CallContext.current().setEventDetails("Load balancer Id: " + newRule.getId());
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_LOAD_BALANCER_CREATE, ipAddr.getAllocatedToAccountId(), ipAddr.getDataCenterId(), newRule.getId(), null, LoadBalancingRule.class.getName(), newRule.getUuid());
return newRule;
} catch (Exception e) {
success = false;
if (e instanceof NetworkRuleConflictException) {
throw (NetworkRuleConflictException) e;
}
throw new CloudRuntimeException("Unable to add rule for ip address id=" + newRule.getSourceIpAddressId(), e);
} finally {
if (!success && newRule != null) {
_firewallMgr.revokeRelatedFirewallRule(newRule.getId(), false);
removeLBRule(newRule);
}
}
}
});
}
Aggregations