Search in sources :

Example 41 with VlanVO

use of com.cloud.dc.VlanVO in project cloudstack by apache.

the class NetworkOrchestrator method deleteVlansInNetwork.

protected boolean deleteVlansInNetwork(final long networkId, final long userId, final Account callerAccount) {
    //cleanup Public vlans
    final List<VlanVO> publicVlans = _vlanDao.listVlansByNetworkId(networkId);
    boolean result = true;
    for (final VlanVO vlan : publicVlans) {
        if (!_configMgr.deleteVlanAndPublicIpRange(userId, vlan.getId(), callerAccount)) {
            s_logger.warn("Failed to delete vlan " + vlan.getId() + ");");
            result = false;
        }
    }
    //cleanup private vlans
    final int privateIpAllocCount = _privateIpDao.countAllocatedByNetworkId(networkId);
    if (privateIpAllocCount > 0) {
        s_logger.warn("Can't delete Private ip range for network " + networkId + " as it has allocated ip addresses");
        result = false;
    } else {
        _privateIpDao.deleteByNetworkId(networkId);
        s_logger.debug("Deleted ip range for private network id=" + networkId);
    }
    return result;
}
Also used : VlanVO(com.cloud.dc.VlanVO)

Example 42 with VlanVO

use of com.cloud.dc.VlanVO in project cloudstack by apache.

the class ExternalFirewallDeviceManagerImpl method manageGuestNetworkWithExternalFirewall.

@Override
public boolean manageGuestNetworkWithExternalFirewall(boolean add, Network network) throws ResourceUnavailableException, InsufficientCapacityException {
    if (network.getTrafficType() != TrafficType.Guest) {
        s_logger.trace("External firewall can only be used for add/remove guest networks.");
        return false;
    }
    long zoneId = network.getDataCenterId();
    DataCenterVO zone = _dcDao.findById(zoneId);
    HostVO externalFirewall = null;
    if (add) {
        GlobalLock deviceMapLock = GlobalLock.getInternLock("NetworkFirewallDeviceMap");
        try {
            if (deviceMapLock.lock(120)) {
                try {
                    ExternalFirewallDeviceVO device = findSuitableFirewallForNetwork(network);
                    long externalFirewallId = device.getId();
                    NetworkExternalFirewallVO networkFW = new NetworkExternalFirewallVO(network.getId(), externalFirewallId);
                    _networkExternalFirewallDao.persist(networkFW);
                    externalFirewall = _hostDao.findById(device.getHostId());
                } finally {
                    deviceMapLock.unlock();
                }
            }
        } finally {
            deviceMapLock.releaseRef();
        }
    } else {
        ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network);
        if (fwDeviceVO == null) {
            s_logger.warn("Network shutdown requested on external firewall element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed.");
            return true;
        }
        externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
    }
    Account account = _accountDao.findByIdIncludingRemoved(network.getAccountId());
    NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
    boolean sharedSourceNat = offering.getSharedSourceNat();
    IPAddressVO sourceNatIp = null;
    if (!sharedSourceNat) {
        // Get the source NAT IP address for this network
        List<? extends IpAddress> sourceNatIps = _networkModel.listPublicIpsAssignedToAccount(network.getAccountId(), zoneId, true);
        for (IpAddress ipAddress : sourceNatIps) {
            if (ipAddress.getAssociatedWithNetworkId().longValue() == network.getId()) {
                sourceNatIp = _ipAddressDao.findById(ipAddress.getId());
                break;
            }
        }
        if (sourceNatIp == null) {
            String errorMsg = "External firewall was unable to find the source NAT IP address for network " + network.getName();
            s_logger.error(errorMsg);
            return true;
        }
    }
    // Send a command to the external firewall to implement or shutdown the guest network
    long guestVlanTag = Long.parseLong(BroadcastDomainType.getValue(network.getBroadcastUri()));
    String guestVlanGateway = network.getGateway();
    String guestVlanCidr = network.getCidr();
    String sourceNatIpAddress = null;
    String publicVlanTag = null;
    if (sourceNatIp != null) {
        sourceNatIpAddress = sourceNatIp.getAddress().addr();
        VlanVO publicVlan = _vlanDao.findById(sourceNatIp.getVlanId());
        publicVlanTag = publicVlan.getVlanTag();
    }
    // Get network rate
    Integer networkRate = _networkModel.getNetworkRate(network.getId(), null);
    IpAddressTO ip = new IpAddressTO(account.getAccountId(), sourceNatIpAddress, add, false, !sharedSourceNat, publicVlanTag, null, null, null, networkRate, false);
    IpAddressTO[] ips = new IpAddressTO[1];
    ips[0] = ip;
    IpAssocCommand cmd = new IpAssocCommand(ips);
    cmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY, guestVlanGateway);
    cmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, guestVlanCidr);
    cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag));
    Answer answer = _agentMgr.easySend(externalFirewall.getId(), cmd);
    List<String> reservedIpAddressesForGuestNetwork = _nicDao.listIpAddressInNetwork(network.getId());
    if (answer == null || !answer.getResult()) {
        String action = add ? "implement" : "shutdown";
        String answerDetails = (answer != null) ? answer.getDetails() : "answer was null";
        String msg = "External firewall was unable to " + action + " the guest network on the external firewall in zone " + zone.getName() + " due to " + answerDetails;
        s_logger.error(msg);
        if (!add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) {
            // If we failed the implementation as well, then just return, no complain
            s_logger.error("Skip the shutdown of guest network on SRX because it seems we didn't implement it as well");
            return true;
        }
        throw new ResourceUnavailableException(msg, DataCenter.class, zoneId);
    }
    if (add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) {
        // Insert a new NIC for this guest network to reserve the gateway address
        _networkMgr.savePlaceholderNic(network, network.getGateway(), null, null);
    }
    // Delete any mappings used for inline external load balancers in this network
    List<NicVO> nicsInNetwork = _nicDao.listByNetworkId(network.getId());
    for (NicVO nic : nicsInNetwork) {
        InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByNicId(nic.getId());
        if (mapping != null) {
            _nicDao.expunge(mapping.getNicId());
            _inlineLoadBalancerNicMapDao.expunge(mapping.getId());
        }
    }
    // on network shutdown, delete placeHolder nics used for the firewall device
    if (!add) {
        List<NicVO> nics = _nicDao.listByNetworkId(network.getId());
        for (NicVO nic : nics) {
            if (nic.getVmType() == null && nic.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && nic.getIPv4Address().equals(network.getGateway())) {
                s_logger.debug("Removing placeholder nic " + nic + " for the network " + network);
                _nicDao.remove(nic.getId());
            }
        }
        freeFirewallForNetwork(network);
    }
    String action = add ? "implemented" : "shut down";
    s_logger.debug("External firewall has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag);
    return true;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) Account(com.cloud.user.Account) ExternalFirewallDeviceVO(com.cloud.network.dao.ExternalFirewallDeviceVO) IpAddressTO(com.cloud.agent.api.to.IpAddressTO) NetworkOffering(com.cloud.offering.NetworkOffering) InlineLoadBalancerNicMapVO(com.cloud.network.dao.InlineLoadBalancerNicMapVO) HostVO(com.cloud.host.HostVO) GlobalLock(com.cloud.utils.db.GlobalLock) Answer(com.cloud.agent.api.Answer) NetworkExternalFirewallVO(com.cloud.network.dao.NetworkExternalFirewallVO) IpAssocCommand(com.cloud.agent.api.routing.IpAssocCommand) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) NicVO(com.cloud.vm.NicVO)

Example 43 with VlanVO

use of com.cloud.dc.VlanVO in project cloudstack by apache.

the class Ipv6AddressManagerImpl method assignDirectIp6Address.

@Override
public UserIpv6Address assignDirectIp6Address(long dcId, Account owner, Long networkId, String requestedIp6) throws InsufficientAddressCapacityException {
    Network network = _networkDao.findById(networkId);
    if (network == null) {
        return null;
    }
    List<VlanVO> vlans = _vlanDao.listVlansByNetworkId(networkId);
    if (vlans == null) {
        s_logger.debug("Cannot find related vlan attached to network " + networkId);
        return null;
    }
    String ip = null;
    Vlan ipVlan = null;
    if (requestedIp6 == null) {
        if (!_networkModel.isIP6AddressAvailableInNetwork(networkId)) {
            throw new InsufficientAddressCapacityException("There is no more address available in the network " + network.getName(), DataCenter.class, network.getDataCenterId());
        }
        for (Vlan vlan : vlans) {
            if (!_networkModel.isIP6AddressAvailableInVlan(vlan.getId())) {
                continue;
            }
            ip = NetUtils.getIp6FromRange(vlan.getIp6Range());
            int count = 0;
            while (_ipv6Dao.findByNetworkIdAndIp(networkId, ip) != null) {
                ip = NetUtils.getNextIp6InRange(ip, vlan.getIp6Range());
                count++;
                // It's an arbitrate number to prevent the infinite loop
                if (count > _ipv6RetryMax) {
                    ip = null;
                    break;
                }
            }
            if (ip != null) {
                ipVlan = vlan;
            }
        }
        if (ip == null) {
            throw new InsufficientAddressCapacityException("Cannot find a usable IP in the network " + network.getName() + " after " + _ipv6RetryMax + "(network.ipv6.search.retry.max) times retry!", DataCenter.class, network.getDataCenterId());
        }
    } else {
        for (Vlan vlan : vlans) {
            if (NetUtils.isIp6InRange(requestedIp6, vlan.getIp6Range())) {
                ipVlan = vlan;
                break;
            }
        }
        if (ipVlan == null) {
            throw new CloudRuntimeException("Requested IPv6 is not in the predefined range!");
        }
        ip = requestedIp6;
        if (_ipv6Dao.findByNetworkIdAndIp(networkId, ip) != null) {
            throw new CloudRuntimeException("The requested IP is already taken!");
        }
    }
    DataCenterVO dc = _dcDao.findById(dcId);
    Long mac = dc.getMacAddress();
    Long nextMac = mac + 1;
    dc.setMacAddress(nextMac);
    _dcDao.update(dc.getId(), dc);
    String macAddress = NetUtils.long2Mac(NetUtils.createSequenceBasedMacAddress(mac, NetworkModel.MACIdentifier.value()));
    UserIpv6AddressVO ipVO = new UserIpv6AddressVO(ip, dcId, macAddress, ipVlan.getId());
    ipVO.setPhysicalNetworkId(network.getPhysicalNetworkId());
    ipVO.setSourceNetworkId(networkId);
    ipVO.setState(UserIpv6Address.State.Allocated);
    ipVO.setDomainId(owner.getDomainId());
    ipVO.setAccountId(owner.getAccountId());
    _ipv6Dao.persist(ipVO);
    return ipVO;
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) Vlan(com.cloud.dc.Vlan) VlanVO(com.cloud.dc.VlanVO)

Example 44 with VlanVO

use of com.cloud.dc.VlanVO in project cloudstack by apache.

the class IpAddressManagerImpl method transferPortableIP.

@DB
@Override
public void transferPortableIP(final long ipAddrId, long currentNetworkId, long newNetworkId) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException {
    Network srcNetwork = _networksDao.findById(currentNetworkId);
    if (srcNetwork == null) {
        throw new InvalidParameterValueException("Invalid source network id " + currentNetworkId + " is given");
    }
    final Network dstNetwork = _networksDao.findById(newNetworkId);
    if (dstNetwork == null) {
        throw new InvalidParameterValueException("Invalid source network id " + newNetworkId + " is given");
    }
    final IPAddressVO ip = _ipAddressDao.findById(ipAddrId);
    if (ip == null) {
        throw new InvalidParameterValueException("Invalid portable ip address id is given");
    }
    assert (isPortableIpTransferableFromNetwork(ipAddrId, currentNetworkId));
    // disassociate portable IP with current network/VPC network
    if (srcNetwork.getVpcId() != null) {
        _vpcMgr.unassignIPFromVpcNetwork(ipAddrId, currentNetworkId);
    } else {
        disassociatePortableIPToGuestNetwork(ipAddrId, currentNetworkId);
    }
    // in user_ip_address and vlan tables so as to emulate portable IP as provisioned in destination data center
    if (srcNetwork.getDataCenterId() != dstNetwork.getDataCenterId()) {
        Transaction.execute(new TransactionCallbackNoReturn() {

            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                long physicalNetworkId = _networkModel.getDefaultPhysicalNetworkByZoneAndTrafficType(dstNetwork.getDataCenterId(), TrafficType.Public).getId();
                long publicNetworkId = _networkModel.getSystemNetworkByZoneAndTrafficType(dstNetwork.getDataCenterId(), TrafficType.Public).getId();
                ip.setDataCenterId(dstNetwork.getDataCenterId());
                ip.setPhysicalNetworkId(physicalNetworkId);
                ip.setSourceNetworkId(publicNetworkId);
                _ipAddressDao.update(ipAddrId, ip);
                VlanVO vlan = _vlanDao.findById(ip.getVlanId());
                vlan.setPhysicalNetworkId(physicalNetworkId);
                vlan.setNetworkId(publicNetworkId);
                vlan.setDataCenterId(dstNetwork.getDataCenterId());
                _vlanDao.update(ip.getVlanId(), vlan);
            }
        });
    }
    // associate portable IP with new network/VPC network
    associatePortableIPToGuestNetwork(ipAddrId, newNetworkId, false);
    Transaction.execute(new TransactionCallbackNoReturn() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            if (dstNetwork.getVpcId() != null) {
                ip.setVpcId(dstNetwork.getVpcId());
            } else {
                ip.setVpcId(null);
            }
            _ipAddressDao.update(ipAddrId, ip);
        }
    });
    // trigger an action event for the transfer of portable IP across the networks, so that external entities
    // monitoring for this event can initiate the route advertisement for the availability of IP from the zoe
    ActionEventUtils.onActionEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, Domain.ROOT_DOMAIN, EventTypes.EVENT_PORTABLE_IP_TRANSFER, "Portable IP associated is transferred from network " + currentNetworkId + " to " + newNetworkId);
}
Also used : InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) TransactionStatus(com.cloud.utils.db.TransactionStatus) IPAddressVO(com.cloud.network.dao.IPAddressVO) TransactionCallbackNoReturn(com.cloud.utils.db.TransactionCallbackNoReturn) VlanVO(com.cloud.dc.VlanVO) DB(com.cloud.utils.db.DB)

Example 45 with VlanVO

use of com.cloud.dc.VlanVO in project cloudstack by apache.

the class NetworkModelImpl method isIP6AddressAvailableInVlan.

@Override
public boolean isIP6AddressAvailableInVlan(long vlanId) {
    VlanVO vlan = _vlanDao.findById(vlanId);
    if (vlan.getIp6Range() == null) {
        return false;
    }
    long existedCount = _ipv6Dao.countExistedIpsInVlan(vlanId);
    BigInteger existedInt = BigInteger.valueOf(existedCount);
    BigInteger rangeInt = NetUtils.countIp6InRange(vlan.getIp6Range());
    return (existedInt.compareTo(rangeInt) < 0);
}
Also used : BigInteger(java.math.BigInteger) VlanVO(com.cloud.dc.VlanVO)

Aggregations

VlanVO (com.cloud.dc.VlanVO)58 ArrayList (java.util.ArrayList)22 IPAddressVO (com.cloud.network.dao.IPAddressVO)15 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)14 DB (com.cloud.utils.db.DB)14 HostVO (com.cloud.host.HostVO)11 Network (com.cloud.network.Network)11 Account (com.cloud.user.Account)11 TransactionStatus (com.cloud.utils.db.TransactionStatus)11 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)11 List (java.util.List)8 Answer (com.cloud.agent.api.Answer)7 AccountVlanMapVO (com.cloud.dc.AccountVlanMapVO)7 DataCenter (com.cloud.dc.DataCenter)7 PublicIp (com.cloud.network.addr.PublicIp)7 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)6 NetworkVO (com.cloud.network.dao.NetworkVO)6 PhysicalNetworkVO (com.cloud.network.dao.PhysicalNetworkVO)6 NetworkOffering (com.cloud.offering.NetworkOffering)6 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)6