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