use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class NetworkServiceImpl method createPrivateNetwork.
@Override
@DB
public Network createPrivateNetwork(final String networkName, final String displayText, long physicalNetworkId, String broadcastUriString, final String startIp, String endIp, final String gateway, String netmask, final long networkOwnerId, final Long vpcId, final Boolean sourceNat, final Long networkOfferingId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException {
final Account owner = _accountMgr.getAccount(networkOwnerId);
// Get system network offering
NetworkOfferingVO ntwkOff = null;
if (networkOfferingId != null) {
ntwkOff = _networkOfferingDao.findById(networkOfferingId);
}
if (ntwkOff == null) {
ntwkOff = findSystemNetworkOffering(NetworkOffering.SystemPrivateGatewayNetworkOffering);
}
// Validate physical network
final PhysicalNetwork pNtwk = _physicalNetworkDao.findById(physicalNetworkId);
if (pNtwk == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find a physical network" + " having the given id");
ex.addProxyObject(String.valueOf(physicalNetworkId), "physicalNetworkId");
throw ex;
}
// if end ip is not specified, default it to startIp
if (!NetUtils.isValidIp(startIp)) {
throw new InvalidParameterValueException("Invalid format for the ip address parameter");
}
if (endIp == null) {
endIp = startIp;
} else if (!NetUtils.isValidIp(endIp)) {
throw new InvalidParameterValueException("Invalid format for the endIp address parameter");
}
if (!NetUtils.isValidIp(gateway)) {
throw new InvalidParameterValueException("Invalid gateway");
}
if (!NetUtils.isValidNetmask(netmask)) {
throw new InvalidParameterValueException("Invalid netmask");
}
final String cidr = NetUtils.ipAndNetMaskToCidr(gateway, netmask);
URI uri = BroadcastDomainType.fromString(broadcastUriString);
final String uriString = uri.toString();
BroadcastDomainType tiep = BroadcastDomainType.getSchemeValue(uri);
// TODO make a test for any supported scheme
if (!(tiep == BroadcastDomainType.Vlan || tiep == BroadcastDomainType.Lswitch)) {
throw new InvalidParameterValueException("unsupported type of broadcastUri specified: " + broadcastUriString);
}
final NetworkOfferingVO ntwkOffFinal = ntwkOff;
try {
return Transaction.execute(new TransactionCallbackWithException<Network, Exception>() {
@Override
public Network doInTransaction(TransactionStatus status) throws ResourceAllocationException, InsufficientCapacityException {
//lock datacenter as we need to get mac address seq from there
DataCenterVO dc = _dcDao.lockRow(pNtwk.getDataCenterId(), true);
//check if we need to create guest network
Network privateNetwork = _networksDao.getPrivateNetwork(uriString, cidr, networkOwnerId, pNtwk.getDataCenterId(), networkOfferingId);
if (privateNetwork == null) {
//create Guest network
privateNetwork = _networkMgr.createGuestNetwork(ntwkOffFinal.getId(), networkName, displayText, gateway, cidr, uriString, null, owner, null, pNtwk, pNtwk.getDataCenterId(), ACLType.Account, null, vpcId, null, null, true, null);
if (privateNetwork != null) {
s_logger.debug("Successfully created guest network " + privateNetwork);
} else {
throw new CloudRuntimeException("Creating guest network failed");
}
} else {
s_logger.debug("Private network already exists: " + privateNetwork);
//Do not allow multiple private gateways with same Vlan within a VPC
if (vpcId != null && vpcId.equals(privateNetwork.getVpcId())) {
throw new InvalidParameterValueException("Private network for the vlan: " + uriString + " and cidr " + cidr + " already exists " + "for Vpc " + vpcId + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
}
}
if (vpcId != null) {
//add entry to private_ip_address table
PrivateIpVO privateIp = _privateIpDao.findByIpAndSourceNetworkIdAndVpcId(privateNetwork.getId(), startIp, vpcId);
if (privateIp != null) {
throw new InvalidParameterValueException("Private ip address " + startIp + " already used for private gateway" + " in zone " + _entityMgr.findById(DataCenter.class, pNtwk.getDataCenterId()).getName());
}
Long mac = dc.getMacAddress();
Long nextMac = mac + 1;
dc.setMacAddress(nextMac);
privateIp = new PrivateIpVO(startIp, privateNetwork.getId(), nextMac, vpcId, sourceNat);
_privateIpDao.persist(privateIp);
_dcDao.update(dc.getId(), dc);
}
s_logger.debug("Private network " + privateNetwork + " is created");
return privateNetwork;
}
});
} catch (Exception e) {
ExceptionUtil.rethrowRuntime(e);
ExceptionUtil.rethrow(e, ResourceAllocationException.class);
ExceptionUtil.rethrow(e, InsufficientCapacityException.class);
throw new IllegalStateException(e);
}
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class NetworkServiceImpl method createPhysicalNetwork.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_PHYSICAL_NETWORK_CREATE, eventDescription = "Creating Physical Network", create = true)
public PhysicalNetwork createPhysicalNetwork(final Long zoneId, final String vnetRange, final String networkSpeed, final List<String> isolationMethods, String broadcastDomainRangeStr, final Long domainId, final List<String> tags, final String name) {
// Check if zone exists
if (zoneId == null) {
throw new InvalidParameterValueException("Please specify a valid zone.");
}
DataCenterVO zone = _dcDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Please specify a valid zone.");
}
if (Grouping.AllocationState.Enabled == zone.getAllocationState()) {
// TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject().
throw new PermissionDeniedException("Cannot create PhysicalNetwork since the Zone is currently enabled, zone Id: " + zoneId);
}
NetworkType zoneType = zone.getNetworkType();
if (zoneType == NetworkType.Basic) {
if (!_physicalNetworkDao.listByZone(zoneId).isEmpty()) {
// TBD: Send uuid instead of zoneId; may have to hardcode tablename in call to addProxyObject().
throw new CloudRuntimeException("Cannot add the physical network to basic zone id: " + zoneId + ", there is a physical network already existing in this basic Zone");
}
}
if (tags != null && tags.size() > 1) {
throw new InvalidParameterException("Only one tag can be specified for a physical network at this time");
}
if (isolationMethods != null && isolationMethods.size() > 1) {
throw new InvalidParameterException("Only one isolationMethod can be specified for a physical network at this time");
}
if (vnetRange != null) {
// Verify zone type
if (zoneType == NetworkType.Basic || (zoneType == NetworkType.Advanced && zone.isSecurityGroupEnabled())) {
throw new InvalidParameterValueException("Can't add vnet range to the physical network in the zone that supports " + zoneType + " network, Security Group enabled: " + zone.isSecurityGroupEnabled());
}
}
BroadcastDomainRange broadcastDomainRange = null;
if (broadcastDomainRangeStr != null && !broadcastDomainRangeStr.isEmpty()) {
try {
broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.valueOf(broadcastDomainRangeStr.toUpperCase());
} catch (IllegalArgumentException ex) {
throw new InvalidParameterValueException("Unable to resolve broadcastDomainRange '" + broadcastDomainRangeStr + "' to a supported value {Pod or Zone}");
}
// in Acton release you can specify only Zone broadcastdomain type in Advance zone, and Pod in Basic
if (zoneType == NetworkType.Basic && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.POD) {
throw new InvalidParameterValueException("Basic zone can have broadcast domain type of value " + BroadcastDomainRange.POD + " only");
} else if (zoneType == NetworkType.Advanced && broadcastDomainRange != null && broadcastDomainRange != BroadcastDomainRange.ZONE) {
throw new InvalidParameterValueException("Advance zone can have broadcast domain type of value " + BroadcastDomainRange.ZONE + " only");
}
}
if (broadcastDomainRange == null) {
if (zoneType == NetworkType.Basic) {
broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.POD;
} else {
broadcastDomainRange = PhysicalNetwork.BroadcastDomainRange.ZONE;
}
}
try {
final BroadcastDomainRange broadcastDomainRangeFinal = broadcastDomainRange;
return Transaction.execute(new TransactionCallback<PhysicalNetworkVO>() {
@Override
public PhysicalNetworkVO doInTransaction(TransactionStatus status) {
// Create the new physical network in the database
long id = _physicalNetworkDao.getNextInSequence(Long.class, "id");
PhysicalNetworkVO pNetwork = new PhysicalNetworkVO(id, zoneId, vnetRange, networkSpeed, domainId, broadcastDomainRangeFinal, name);
pNetwork.setTags(tags);
pNetwork.setIsolationMethods(isolationMethods);
pNetwork = _physicalNetworkDao.persist(pNetwork);
// Add vnet entries for the new zone if zone type is Advanced
if (vnetRange != null) {
addOrRemoveVnets(vnetRange.split(","), pNetwork);
}
// add VirtualRouter as the default network service provider
addDefaultVirtualRouterToPhysicalNetwork(pNetwork.getId());
if (pNetwork.getIsolationMethods().contains("GRE"))
addDefaultOvsToPhysicalNetwork(pNetwork.getId());
// add security group provider to the physical network
addDefaultSecurityGroupProviderToPhysicalNetwork(pNetwork.getId());
// add VPCVirtualRouter as the defualt network service provider
addDefaultVpcVirtualRouterToPhysicalNetwork(pNetwork.getId());
// add baremetal as the defualt network service provider
addDefaultBaremetalProvidersToPhysicalNetwork(pNetwork.getId());
//Add Internal Load Balancer element as a default network service provider
addDefaultInternalLbProviderToPhysicalNetwork(pNetwork.getId());
return pNetwork;
}
});
} catch (Exception ex) {
s_logger.warn("Exception: ", ex);
throw new CloudRuntimeException("Fail to create a physical network");
}
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class NetworkServiceImpl method releaseSecondaryIpFromNic.
@Override
@DB
@ActionEvent(eventType = EventTypes.EVENT_NIC_SECONDARY_IP_UNASSIGN, eventDescription = "Removing secondary ip " + "from nic", async = true)
public boolean releaseSecondaryIpFromNic(long ipAddressId) {
Account caller = CallContext.current().getCallingAccount();
boolean success = false;
// Verify input parameters
NicSecondaryIpVO secIpVO = _nicSecondaryIpDao.findById(ipAddressId);
if (secIpVO == null) {
throw new InvalidParameterValueException("Unable to find secondary ip address by id");
}
VirtualMachine vm = _userVmDao.findById(secIpVO.getVmId());
if (vm == null) {
throw new InvalidParameterValueException("There is no vm with the given secondary ip");
}
// verify permissions
_accountMgr.checkAccess(caller, null, true, vm);
Network network = _networksDao.findById(secIpVO.getNetworkId());
if (network == null) {
throw new InvalidParameterValueException("Invalid network id is given");
}
// Validate network offering
NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(network.getNetworkOfferingId());
Long nicId = secIpVO.getNicId();
s_logger.debug("ip id = " + ipAddressId + " nic id = " + nicId);
//check is this the last secondary ip for NIC
List<NicSecondaryIpVO> ipList = _nicSecondaryIpDao.listByNicId(nicId);
boolean lastIp = false;
if (ipList.size() == 1) {
// this is the last secondary ip to nic
lastIp = true;
}
DataCenter dc = _dcDao.findById(network.getDataCenterId());
if (dc == null) {
throw new InvalidParameterValueException("Invalid zone Id is given");
}
s_logger.debug("Calling secondary ip " + secIpVO.getIp4Address() + " release ");
if (dc.getNetworkType() == NetworkType.Advanced && network.getGuestType() == Network.GuestType.Isolated) {
//check PF or static NAT is configured on this ip address
String secondaryIp = secIpVO.getIp4Address();
List<FirewallRuleVO> fwRulesList = _firewallDao.listByNetworkAndPurpose(network.getId(), Purpose.PortForwarding);
if (fwRulesList.size() != 0) {
for (FirewallRuleVO rule : fwRulesList) {
if (_portForwardingDao.findByIdAndIp(rule.getId(), secondaryIp) != null) {
s_logger.debug("VM nic IP " + secondaryIp + " is associated with the port forwarding rule");
throw new InvalidParameterValueException("Can't remove the secondary ip " + secondaryIp + " is associate with the port forwarding rule");
}
}
}
//check if the secondary ip associated with any static nat rule
IPAddressVO publicIpVO = _ipAddressDao.findByIpAndNetworkId(secIpVO.getNetworkId(), secondaryIp);
if (publicIpVO != null) {
s_logger.debug("VM nic IP " + secondaryIp + " is associated with the static NAT rule public IP address id " + publicIpVO.getId());
throw new InvalidParameterValueException("Can' remove the ip " + secondaryIp + "is associate with static NAT rule public IP address id " + publicIpVO.getId());
}
if (_loadBalancerDao.isLoadBalancerRulesMappedToVmGuestIp(vm.getId(), secondaryIp, network.getId())) {
s_logger.debug("VM nic IP " + secondaryIp + " is mapped to load balancing rule");
throw new InvalidParameterValueException("Can't remove the secondary ip " + secondaryIp + " is mapped to load balancing rule");
}
} else if (dc.getNetworkType() == NetworkType.Basic || ntwkOff.getGuestType() == Network.GuestType.Shared) {
final IPAddressVO ip = _ipAddressDao.findByIpAndSourceNetworkId(secIpVO.getNetworkId(), secIpVO.getIp4Address());
if (ip != null) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
_ipAddrMgr.markIpAsUnavailable(ip.getId());
_ipAddressDao.unassignIpAddress(ip.getId());
}
});
}
} else {
throw new InvalidParameterValueException("Not supported for this network now");
}
success = removeNicSecondaryIP(secIpVO, lastIp);
return success;
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class AutoScaleManagerImpl method checkValidityAndPersist.
@DB
protected AutoScaleVmGroupVO checkValidityAndPersist(final AutoScaleVmGroupVO vmGroup, final List<Long> passedScaleUpPolicyIds, final List<Long> passedScaleDownPolicyIds) {
int minMembers = vmGroup.getMinMembers();
int maxMembers = vmGroup.getMaxMembers();
int interval = vmGroup.getInterval();
List<Counter> counters = new ArrayList<Counter>();
List<AutoScalePolicyVO> policies = new ArrayList<AutoScalePolicyVO>();
final List<Long> policyIds = new ArrayList<Long>();
List<Long> currentScaleUpPolicyIds = new ArrayList<Long>();
List<Long> currentScaleDownPolicyIds = new ArrayList<Long>();
if (vmGroup.getCreated() != null) {
ApiDBUtils.getAutoScaleVmGroupPolicyIds(vmGroup.getId(), currentScaleUpPolicyIds, currentScaleDownPolicyIds);
}
if (minMembers < 0) {
throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " is an invalid value: " + minMembers);
}
if (maxMembers < 0) {
throw new InvalidParameterValueException(ApiConstants.MAX_MEMBERS + " is an invalid value: " + maxMembers);
}
if (minMembers > maxMembers) {
throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " (" + minMembers + ")cannot be greater than " + ApiConstants.MAX_MEMBERS + " (" + maxMembers + ")");
}
if (interval < 0) {
throw new InvalidParameterValueException("interval is an invalid value: " + interval);
}
if (passedScaleUpPolicyIds != null) {
policies.addAll(getAutoScalePolicies("scaleuppolicyid", passedScaleUpPolicyIds, counters, interval, true));
policyIds.addAll(passedScaleUpPolicyIds);
} else {
// Run the interval check for existing policies
getAutoScalePolicies("scaleuppolicyid", currentScaleUpPolicyIds, counters, interval, true);
policyIds.addAll(currentScaleUpPolicyIds);
}
if (passedScaleDownPolicyIds != null) {
policies.addAll(getAutoScalePolicies("scaledownpolicyid", passedScaleDownPolicyIds, counters, interval, false));
policyIds.addAll(passedScaleDownPolicyIds);
} else {
// Run the interval check for existing policies
getAutoScalePolicies("scaledownpolicyid", currentScaleDownPolicyIds, counters, interval, false);
policyIds.addAll(currentScaleDownPolicyIds);
}
AutoScaleVmProfileVO profileVO = getEntityInDatabase(CallContext.current().getCallingAccount(), ApiConstants.VMPROFILE_ID, vmGroup.getProfileId(), _autoScaleVmProfileDao);
LoadBalancerVO loadBalancer = getEntityInDatabase(CallContext.current().getCallingAccount(), ApiConstants.LBID, vmGroup.getLoadBalancerId(), _lbDao);
validateAutoScaleCounters(loadBalancer.getNetworkId(), counters, profileVO.getCounterParams());
ControlledEntity[] sameOwnerEntities = policies.toArray(new ControlledEntity[policies.size() + 2]);
sameOwnerEntities[sameOwnerEntities.length - 2] = loadBalancer;
sameOwnerEntities[sameOwnerEntities.length - 1] = profileVO;
_accountMgr.checkAccess(CallContext.current().getCallingAccount(), null, true, sameOwnerEntities);
return Transaction.execute(new TransactionCallback<AutoScaleVmGroupVO>() {
@Override
public AutoScaleVmGroupVO doInTransaction(TransactionStatus status) {
AutoScaleVmGroupVO vmGroupNew = _autoScaleVmGroupDao.persist(vmGroup);
if (passedScaleUpPolicyIds != null || passedScaleDownPolicyIds != null) {
_autoScaleVmGroupPolicyMapDao.removeByGroupId(vmGroupNew.getId());
for (Long policyId : policyIds) {
_autoScaleVmGroupPolicyMapDao.persist(new AutoScaleVmGroupPolicyMapVO(vmGroupNew.getId(), policyId));
}
}
return vmGroupNew;
}
});
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class DefaultVMSnapshotStrategy method processAnswer.
@DB
protected void processAnswer(final VMSnapshotVO vmSnapshot, UserVm userVm, final Answer as, Long hostId) {
try {
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<NoTransitionException>() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) throws NoTransitionException {
if (as instanceof CreateVMSnapshotAnswer) {
CreateVMSnapshotAnswer answer = (CreateVMSnapshotAnswer) as;
finalizeCreate(vmSnapshot, answer.getVolumeTOs());
vmSnapshotHelper.vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationSucceeded);
} else if (as instanceof RevertToVMSnapshotAnswer) {
RevertToVMSnapshotAnswer answer = (RevertToVMSnapshotAnswer) as;
finalizeRevert(vmSnapshot, answer.getVolumeTOs());
vmSnapshotHelper.vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationSucceeded);
} else if (as instanceof DeleteVMSnapshotAnswer) {
DeleteVMSnapshotAnswer answer = (DeleteVMSnapshotAnswer) as;
finalizeDelete(vmSnapshot, answer.getVolumeTOs());
vmSnapshotDao.remove(vmSnapshot.getId());
}
}
});
} catch (Exception e) {
String errMsg = "Error while process answer: " + as.getClass() + " due to " + e.getMessage();
s_logger.error(errMsg, e);
throw new CloudRuntimeException(errMsg);
}
}
Aggregations