use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class NetworkOrchestrator method importNic.
@DB
@Override
public Pair<NicProfile, Integer> importNic(final String macAddress, int deviceId, final Network network, final Boolean isDefaultNic, final VirtualMachine vm, final Network.IpAddresses ipAddresses, final boolean forced) throws ConcurrentOperationException, InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
s_logger.debug("Allocating nic for vm " + vm.getUuid() + " in network " + network + " during import");
String guestIp = null;
if (ipAddresses != null && StringUtils.isNotEmpty(ipAddresses.getIp4Address())) {
if (ipAddresses.getIp4Address().equals("auto")) {
ipAddresses.setIp4Address(null);
}
if (network.getGuestType() != GuestType.L2) {
guestIp = _ipAddrMgr.acquireGuestIpAddress(network, ipAddresses.getIp4Address());
} else {
guestIp = null;
}
if (guestIp == null && network.getGuestType() != GuestType.L2 && !_networkModel.listNetworkOfferingServices(network.getNetworkOfferingId()).isEmpty()) {
throw new InsufficientVirtualNetworkCapacityException("Unable to acquire Guest IP address for network " + network, DataCenter.class, network.getDataCenterId());
}
}
final String finalGuestIp = guestIp;
final NicVO vo = Transaction.execute(new TransactionCallback<NicVO>() {
@Override
public NicVO doInTransaction(TransactionStatus status) {
NicVO existingNic = _nicDao.findByNetworkIdAndMacAddress(network.getId(), macAddress);
if (existingNic != null) {
if (!forced) {
throw new CloudRuntimeException("NIC with MAC address = " + macAddress + " exists on network with ID = " + network.getId() + " and forced flag is disabled");
}
s_logger.debug("Removing existing NIC with MAC address = " + macAddress + " on network with ID = " + network.getId());
existingNic.setState(Nic.State.Deallocating);
existingNic.setRemoved(new Date());
_nicDao.update(existingNic.getId(), existingNic);
}
NicVO vo = new NicVO(network.getGuruName(), vm.getId(), network.getId(), vm.getType());
vo.setMacAddress(macAddress);
vo.setAddressFormat(Networks.AddressFormat.Ip4);
if (NetUtils.isValidIp4(finalGuestIp) && StringUtils.isNotEmpty(network.getGateway())) {
vo.setIPv4Address(finalGuestIp);
vo.setIPv4Gateway(network.getGateway());
if (StringUtils.isNotEmpty(network.getCidr())) {
vo.setIPv4Netmask(NetUtils.cidr2Netmask(network.getCidr()));
}
}
vo.setBroadcastUri(network.getBroadcastUri());
vo.setMode(network.getMode());
vo.setState(Nic.State.Reserved);
vo.setReservationStrategy(ReservationStrategy.Start);
vo.setReservationId(UUID.randomUUID().toString());
vo.setIsolationUri(network.getBroadcastUri());
vo.setDeviceId(deviceId);
vo.setDefaultNic(isDefaultNic);
vo = _nicDao.persist(vo);
int count = 1;
if (vo.getVmType() == VirtualMachine.Type.User) {
s_logger.debug("Changing active number of nics for network id=" + network.getUuid() + " on " + count);
_networksDao.changeActiveNicsBy(network.getId(), count);
}
if (vo.getVmType() == VirtualMachine.Type.User || vo.getVmType() == VirtualMachine.Type.DomainRouter && _networksDao.findById(network.getId()).getTrafficType() == TrafficType.Guest) {
_networksDao.setCheckForGc(network.getId());
}
return vo;
}
});
final Integer networkRate = _networkModel.getNetworkRate(network.getId(), vm.getId());
final NicProfile vmNic = new NicProfile(vo, network, vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(), network));
return new Pair<NicProfile, Integer>(vmNic, Integer.valueOf(deviceId));
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class NetworkOrchestrator method reallocate.
@DB
@Override
public boolean reallocate(final VirtualMachineProfile vm, final DataCenterDeployment dest) throws InsufficientCapacityException, ConcurrentOperationException {
final VMInstanceVO vmInstance = _vmDao.findById(vm.getId());
final DataCenterVO dc = _dcDao.findById(vmInstance.getDataCenterId());
if (dc.getNetworkType() == NetworkType.Basic) {
final List<NicVO> nics = _nicDao.listByVmId(vmInstance.getId());
final NetworkVO network = _networksDao.findById(nics.get(0).getNetworkId());
final LinkedHashMap<Network, List<? extends NicProfile>> profiles = new LinkedHashMap<Network, List<? extends NicProfile>>();
profiles.put(network, new ArrayList<NicProfile>());
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<InsufficientCapacityException>() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) throws InsufficientCapacityException {
cleanupNics(vm);
allocate(vm, profiles, null);
}
});
}
return true;
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class NetworkOrchestrator method cleanupConfigForServicesInNetwork.
@Override
public void cleanupConfigForServicesInNetwork(List<String> services, final Network network) {
long networkId = network.getId();
Account caller = _accountDao.findById(Account.ACCOUNT_ID_SYSTEM);
long userId = User.UID_SYSTEM;
// remove all PF/Static Nat rules for the network
s_logger.info("Services:" + services + " are no longer supported in network:" + network.getUuid() + " after applying new network offering:" + network.getNetworkOfferingId() + " removing the related configuration");
if (services.contains(Service.StaticNat.getName()) || services.contains(Service.PortForwarding.getName())) {
try {
if (_rulesMgr.revokeAllPFStaticNatRulesForNetwork(networkId, userId, caller)) {
s_logger.debug("Successfully cleaned up portForwarding/staticNat rules for network id=" + networkId);
} else {
s_logger.warn("Failed to release portForwarding/StaticNat rules as a part of network id=" + networkId + " cleanup");
}
if (services.contains(Service.StaticNat.getName())) {
// removing static nat configured on ips.
// optimizing the db operations using transaction.
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
List<IPAddressVO> ips = _ipAddressDao.listStaticNatPublicIps(network.getId());
for (IPAddressVO ip : ips) {
ip.setOneToOneNat(false);
ip.setAssociatedWithVmId(null);
ip.setVmIp(null);
_ipAddressDao.update(ip.getId(), ip);
}
}
});
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to release portForwarding/StaticNat rules as a part of network id=" + networkId + " cleanup due to resourceUnavailable ", ex);
}
}
if (services.contains(Service.SourceNat.getName())) {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
List<IPAddressVO> ips = _ipAddressDao.listByAssociatedNetwork(network.getId(), true);
// removing static nat configured on ips.
for (IPAddressVO ip : ips) {
ip.setSourceNat(false);
_ipAddressDao.update(ip.getId(), ip);
}
}
});
}
if (services.contains(Service.Lb.getName())) {
// remove all LB rules for the network
if (_lbMgr.removeAllLoadBalanacersForNetwork(networkId, caller, userId)) {
s_logger.debug("Successfully cleaned up load balancing rules for network id=" + networkId);
} else {
s_logger.warn("Failed to cleanup LB rules as a part of network id=" + networkId + " cleanup");
}
}
if (services.contains(Service.Firewall.getName())) {
// revoke all firewall rules for the network
try {
if (_firewallMgr.revokeAllFirewallRulesForNetwork(networkId, userId, caller)) {
s_logger.debug("Successfully cleaned up firewallRules rules for network id=" + networkId);
} else {
s_logger.warn("Failed to cleanup Firewall rules as a part of network id=" + networkId + " cleanup");
}
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup Firewall rules as a part of network id=" + networkId + " cleanup due to resourceUnavailable ", ex);
}
}
// do not remove vpn service for vpc networks.
if (services.contains(Service.Vpn.getName()) && network.getVpcId() == null) {
RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findByAccountAndNetwork(network.getAccountId(), networkId);
try {
_vpnMgr.destroyRemoteAccessVpnForIp(vpn.getServerAddressId(), caller, true);
} catch (ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup remote access vpn resources of network:" + network.getUuid() + " due to Exception: ", ex);
}
}
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class NetworkOrchestrator method removeDhcpServiceInSubnet.
@DB
@Override
public void removeDhcpServiceInSubnet(final Nic nic) {
final Network network = _networksDao.findById(nic.getNetworkId());
final DhcpServiceProvider dhcpServiceProvider = getDhcpServiceProvider(network);
try {
final NicIpAliasVO ipAlias = _nicIpAliasDao.findByGatewayAndNetworkIdAndState(nic.getIPv4Gateway(), network.getId(), NicIpAlias.State.active);
if (ipAlias != null) {
ipAlias.setState(NicIpAlias.State.revoked);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
_nicIpAliasDao.update(ipAlias.getId(), ipAlias);
final IPAddressVO aliasIpaddressVo = _publicIpAddressDao.findByIpAndSourceNetworkId(ipAlias.getNetworkId(), ipAlias.getIp4Address());
_publicIpAddressDao.unassignIpAddress(aliasIpaddressVo.getId());
}
});
if (!dhcpServiceProvider.removeDhcpSupportForSubnet(network)) {
s_logger.warn("Failed to remove the ip alias on the router, marking it as removed in db and freed the allocated ip " + ipAlias.getIp4Address());
}
}
} catch (final ResourceUnavailableException e) {
// failed to remove the dhcpconfig on the router.
s_logger.info("Unable to delete the ip alias due to unable to contact the virtualrouter.");
}
}
use of com.cloud.utils.db.TransactionStatus in project cloudstack by apache.
the class BrocadeVcsElement method addBrocadeVcsDevice.
@Override
@DB
public BrocadeVcsDeviceVO addBrocadeVcsDevice(AddBrocadeVcsDeviceCmd cmd) {
ServerResource resource = new BrocadeVcsResource();
final String deviceName = Network.Provider.BrocadeVcs.getName();
NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName);
if (networkDevice == null) {
throw new CloudRuntimeException("No network device found for " + deviceName);
}
final Long physicalNetworkId = cmd.getPhysicalNetworkId();
PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId);
}
long zoneId = physicalNetwork.getDataCenterId();
final PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder());
if (ntwkSvcProvider == null) {
throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder() + " is not enabled in the physical network: " + physicalNetworkId + "to add this device");
} else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device");
}
Map<String, String> params = new HashMap<String, String>();
params.put("guid", UUID.randomUUID().toString());
params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId()));
params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId()));
params.put("name", "Brocade VCS - " + cmd.getHost());
params.put("ip", cmd.getHost());
params.put("adminuser", cmd.getUsername());
params.put("adminpass", cmd.getPassword());
Map<String, Object> hostdetails = new HashMap<String, Object>();
hostdetails.putAll(params);
try {
resource.configure(cmd.getHost(), hostdetails);
final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params);
if (host != null) {
return Transaction.execute(new TransactionCallback<BrocadeVcsDeviceVO>() {
@Override
public BrocadeVcsDeviceVO doInTransaction(TransactionStatus status) {
BrocadeVcsDeviceVO brocadeVcsDevice = new BrocadeVcsDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName);
_brocadeVcsDao.persist(brocadeVcsDevice);
DetailVO detail = new DetailVO(host.getId(), "brocadevcsdeviceid", String.valueOf(brocadeVcsDevice.getId()));
_hostDetailsDao.persist(detail);
return brocadeVcsDevice;
}
});
} else {
throw new CloudRuntimeException("Failed to add Brocade VCS Switch due to internal error.");
}
} catch (ConfigurationException e) {
throw new CloudRuntimeException(e.getMessage());
}
}
Aggregations