Search in sources :

Example 31 with TransactionStatus

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));
}
Also used : CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InsufficientVirtualNetworkCapacityException(com.cloud.exception.InsufficientVirtualNetworkCapacityException) TransactionStatus(com.cloud.utils.db.TransactionStatus) NicProfile(com.cloud.vm.NicProfile) NicVO(com.cloud.vm.NicVO) Date(java.util.Date) Pair(com.cloud.utils.Pair) DB(com.cloud.utils.db.DB)

Example 32 with TransactionStatus

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;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) NetworkVO(com.cloud.network.dao.NetworkVO) VMInstanceVO(com.cloud.vm.VMInstanceVO) TransactionStatus(com.cloud.utils.db.TransactionStatus) NicProfile(com.cloud.vm.NicProfile) LinkedHashMap(java.util.LinkedHashMap) Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) LinkedList(java.util.LinkedList) ArrayList(java.util.ArrayList) List(java.util.List) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) NicVO(com.cloud.vm.NicVO) DB(com.cloud.utils.db.DB)

Example 33 with TransactionStatus

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);
        }
    }
}
Also used : Account(com.cloud.user.Account) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) LinkedList(java.util.LinkedList) ArrayList(java.util.ArrayList) List(java.util.List) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 34 with TransactionStatus

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.");
    }
}
Also used : Network(com.cloud.network.Network) PhysicalNetwork(com.cloud.network.PhysicalNetwork) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) TransactionStatus(com.cloud.utils.db.TransactionStatus) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) IPAddressVO(com.cloud.network.dao.IPAddressVO) NicIpAliasVO(com.cloud.vm.dao.NicIpAliasVO) DhcpServiceProvider(com.cloud.network.element.DhcpServiceProvider) DB(com.cloud.utils.db.DB)

Example 35 with TransactionStatus

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());
    }
}
Also used : HashMap(java.util.HashMap) NetworkDevice(org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice) ServerResource(com.cloud.resource.ServerResource) TransactionStatus(com.cloud.utils.db.TransactionStatus) Host(com.cloud.host.Host) BrocadeVcsDeviceVO(com.cloud.network.BrocadeVcsDeviceVO) BrocadeVcsResource(com.cloud.network.resource.BrocadeVcsResource) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) DetailVO(com.cloud.host.DetailVO) ConfigurationException(javax.naming.ConfigurationException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) PhysicalNetworkServiceProviderVO(com.cloud.network.dao.PhysicalNetworkServiceProviderVO) PhysicalNetworkVO(com.cloud.network.dao.PhysicalNetworkVO) DB(com.cloud.utils.db.DB)

Aggregations

TransactionStatus (com.cloud.utils.db.TransactionStatus)323 DB (com.cloud.utils.db.DB)257 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)172 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)150 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)117 ArrayList (java.util.ArrayList)104 Account (com.cloud.user.Account)93 List (java.util.List)89 ActionEvent (com.cloud.event.ActionEvent)88 ConfigurationException (javax.naming.ConfigurationException)71 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)64 InvalidParameterValueException (com.cloud.utils.exception.InvalidParameterValueException)64 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)50 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)49 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)47 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)45 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)45 IPAddressVO (com.cloud.network.dao.IPAddressVO)43 HashMap (java.util.HashMap)38 Network (com.cloud.network.Network)37