Search in sources :

Example 61 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class RemoteAccessVpnManagerImpl method createRemoteAccessVpn.

@Override
@DB
public RemoteAccessVpn createRemoteAccessVpn(final long publicIpId, String ipRange, boolean openFirewall, final Boolean forDisplay) throws NetworkRuleConflictException {
    CallContext ctx = CallContext.current();
    final Account caller = ctx.getCallingAccount();
    Long networkId = null;
    // make sure ip address exists
    final PublicIpAddress ipAddr = _networkMgr.getPublicIpAddress(publicIpId);
    if (ipAddr == null) {
        throw new InvalidParameterValueException("Unable to create remote access vpn, invalid public IP address id" + publicIpId);
    }
    _accountMgr.checkAccess(caller, null, true, ipAddr);
    if (!ipAddr.readyToUse()) {
        throw new InvalidParameterValueException("The Ip address is not ready to be used yet: " + ipAddr.getAddress());
    }
    IPAddressVO ipAddress = _ipAddressDao.findById(publicIpId);
    networkId = ipAddress.getAssociatedWithNetworkId();
    if (networkId != null) {
        _networkMgr.checkIpForService(ipAddress, Service.Vpn, null);
    }
    final Long vpcId = ipAddress.getVpcId();
    /* IP Address used for VPC must be the source NAT IP of whole VPC */
    if (vpcId != null && ipAddress.isSourceNat()) {
        assert networkId == null;
        // No firewall setting for VPC, it would be open internally
        openFirewall = false;
    }
    final boolean openFirewallFinal = openFirewall;
    if (networkId == null && vpcId == null) {
        throw new InvalidParameterValueException("Unable to create remote access vpn for the ipAddress: " + ipAddr.getAddress().addr() + " as ip is not associated with any network or VPC");
    }
    RemoteAccessVpnVO vpnVO = _remoteAccessVpnDao.findByPublicIpAddress(publicIpId);
    if (vpnVO != null) {
        //if vpn is in Added state, return it to the api
        if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
            return vpnVO;
        }
        throw new InvalidParameterValueException("A Remote Access VPN already exists for this public Ip address");
    }
    if (ipRange == null) {
        ipRange = RemoteAccessVpnClientIpRange.valueIn(ipAddr.getAccountId());
    }
    final String[] range = ipRange.split("-");
    if (range.length != 2) {
        throw new InvalidParameterValueException("Invalid ip range");
    }
    if (!NetUtils.isValidIp(range[0]) || !NetUtils.isValidIp(range[1])) {
        throw new InvalidParameterValueException("Invalid ip in range specification " + ipRange);
    }
    if (!NetUtils.validIpRange(range[0], range[1])) {
        throw new InvalidParameterValueException("Invalid ip range " + ipRange);
    }
    Pair<String, Integer> cidr = null;
    // TODO: assumes one virtual network / domr per account per zone
    if (networkId != null) {
        vpnVO = _remoteAccessVpnDao.findByAccountAndNetwork(ipAddr.getAccountId(), networkId);
        if (vpnVO != null) {
            //if vpn is in Added state, return it to the api
            if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
                return vpnVO;
            }
            throw new InvalidParameterValueException("A Remote Access VPN already exists for this account");
        }
        //Verify that vpn service is enabled for the network
        Network network = _networkMgr.getNetwork(networkId);
        if (!_networkMgr.areServicesSupportedInNetwork(network.getId(), Service.Vpn)) {
            throw new InvalidParameterValueException("Vpn service is not supported in network id=" + ipAddr.getAssociatedWithNetworkId());
        }
        cidr = NetUtils.getCidr(network.getCidr());
    } else {
        // Don't need to check VPC because there is only one IP(source NAT IP) available for VPN
        Vpc vpc = _vpcDao.findById(vpcId);
        cidr = NetUtils.getCidr(vpc.getCidr());
    }
    // FIXME: This check won't work for the case where the guest ip range
    // changes depending on the vlan allocated.
    String[] guestIpRange = NetUtils.getIpRangeFromCidr(cidr.first(), cidr.second());
    if (NetUtils.ipRangesOverlap(range[0], range[1], guestIpRange[0], guestIpRange[1])) {
        throw new InvalidParameterValueException("Invalid ip range: " + ipRange + " overlaps with guest ip range " + guestIpRange[0] + "-" + guestIpRange[1]);
    }
    // TODO: check sufficient range
    // TODO: check overlap with private and public ip ranges in datacenter
    long startIp = NetUtils.ip2Long(range[0]);
    final String newIpRange = NetUtils.long2Ip(++startIp) + "-" + range[1];
    final String sharedSecret = PasswordGenerator.generatePresharedKey(_pskLength);
    return Transaction.execute(new TransactionCallbackWithException<RemoteAccessVpn, NetworkRuleConflictException>() {

        @Override
        public RemoteAccessVpn doInTransaction(TransactionStatus status) throws NetworkRuleConflictException {
            if (vpcId == null) {
                _rulesMgr.reservePorts(ipAddr, NetUtils.UDP_PROTO, Purpose.Vpn, openFirewallFinal, caller, NetUtils.VPN_PORT, NetUtils.VPN_L2TP_PORT, NetUtils.VPN_NATT_PORT);
            }
            RemoteAccessVpnVO vpnVO = new RemoteAccessVpnVO(ipAddr.getAccountId(), ipAddr.getDomainId(), ipAddr.getAssociatedWithNetworkId(), publicIpId, vpcId, range[0], newIpRange, sharedSecret);
            if (forDisplay != null) {
                vpnVO.setDisplay(forDisplay);
            }
            return _remoteAccessVpnDao.persist(vpnVO);
        }
    });
}
Also used : Account(com.cloud.user.Account) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) Vpc(com.cloud.network.vpc.Vpc) TransactionStatus(com.cloud.utils.db.TransactionStatus) CallContext(org.apache.cloudstack.context.CallContext) NetworkRuleConflictException(com.cloud.exception.NetworkRuleConflictException) PublicIpAddress(com.cloud.network.PublicIpAddress) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Network(com.cloud.network.Network) IPAddressVO(com.cloud.network.dao.IPAddressVO) RemoteAccessVpn(com.cloud.network.RemoteAccessVpn) DB(com.cloud.utils.db.DB)

Example 62 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class VpcManagerImpl method cleanupVpcResources.

public boolean cleanupVpcResources(final long vpcId, final Account caller, final long callerUserId) throws ResourceUnavailableException, ConcurrentOperationException {
    s_logger.debug("Cleaning up resources for vpc id=" + vpcId);
    boolean success = true;
    // 1) Remove VPN connections and VPN gateway
    s_logger.debug("Cleaning up existed site to site VPN connections");
    _s2sVpnMgr.cleanupVpnConnectionByVpc(vpcId);
    s_logger.debug("Cleaning up existed site to site VPN gateways");
    _s2sVpnMgr.cleanupVpnGatewayByVpc(vpcId);
    // 2) release all ip addresses
    final List<IPAddressVO> ipsToRelease = _ipAddressDao.listByAssociatedVpc(vpcId, null);
    s_logger.debug("Releasing ips for vpc id=" + vpcId + " as a part of vpc cleanup");
    for (final IPAddressVO ipToRelease : ipsToRelease) {
        if (ipToRelease.isPortable()) {
            // portable IP address are associated with owner, until
            // explicitly requested to be disassociated.
            // so as part of VPC clean up just break IP association with VPC
            ipToRelease.setVpcId(null);
            ipToRelease.setAssociatedWithNetworkId(null);
            _ipAddressDao.update(ipToRelease.getId(), ipToRelease);
            s_logger.debug("Portable IP address " + ipToRelease + " is no longer associated with any VPC");
        } else {
            success = success && _ipAddrMgr.disassociatePublicIpAddress(ipToRelease.getId(), callerUserId, caller);
            if (!success) {
                s_logger.warn("Failed to cleanup ip " + ipToRelease + " as a part of vpc id=" + vpcId + " cleanup");
            }
        }
    }
    if (success) {
        s_logger.debug("Released ip addresses for vpc id=" + vpcId + " as a part of cleanup vpc process");
    } else {
        s_logger.warn("Failed to release ip addresses for vpc id=" + vpcId + " as a part of cleanup vpc process");
    // although it failed, proceed to the next cleanup step as it
    // doesn't depend on the public ip release
    }
    // 3) Delete all static route rules
    if (!revokeStaticRoutesForVpc(vpcId, caller)) {
        s_logger.warn("Failed to revoke static routes for vpc " + vpcId + " as a part of cleanup vpc process");
        return false;
    }
    // 4) Delete private gateways
    final List<PrivateGateway> gateways = getVpcPrivateGateways(vpcId);
    if (gateways != null) {
        for (final PrivateGateway gateway : gateways) {
            if (gateway != null) {
                s_logger.debug("Deleting private gateway " + gateway + " as a part of vpc " + vpcId + " resources cleanup");
                if (!deleteVpcPrivateGateway(gateway.getId())) {
                    success = false;
                    s_logger.debug("Failed to delete private gateway " + gateway + " as a part of vpc " + vpcId + " resources cleanup");
                } else {
                    s_logger.debug("Deleted private gateway " + gateway + " as a part of vpc " + vpcId + " resources cleanup");
                }
            }
        }
    }
    //5) Delete ACLs
    final SearchBuilder<NetworkACLVO> searchBuilder = _networkAclDao.createSearchBuilder();
    searchBuilder.and("vpcId", searchBuilder.entity().getVpcId(), Op.IN);
    final SearchCriteria<NetworkACLVO> searchCriteria = searchBuilder.create();
    searchCriteria.setParameters("vpcId", vpcId, 0);
    final Filter filter = new Filter(NetworkACLVO.class, "id", false, null, null);
    final Pair<List<NetworkACLVO>, Integer> aclsCountPair = _networkAclDao.searchAndCount(searchCriteria, filter);
    final List<NetworkACLVO> acls = aclsCountPair.first();
    for (final NetworkACLVO networkAcl : acls) {
        if (networkAcl.getId() != NetworkACL.DEFAULT_ALLOW && networkAcl.getId() != NetworkACL.DEFAULT_DENY) {
            _networkAclMgr.deleteNetworkACL(networkAcl);
        }
    }
    return success;
}
Also used : Filter(com.cloud.utils.db.Filter) IPAddressVO(com.cloud.network.dao.IPAddressVO) ArrayList(java.util.ArrayList) List(java.util.List)

Example 63 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class VpcManagerImpl method assignSourceNatIpAddressToVpc.

@Override
public PublicIp assignSourceNatIpAddressToVpc(final Account owner, final Vpc vpc) throws InsufficientAddressCapacityException, ConcurrentOperationException {
    final long dcId = vpc.getZoneId();
    final IPAddressVO sourceNatIp = getExistingSourceNatInVpc(owner.getId(), vpc.getId());
    PublicIp ipToReturn = null;
    if (sourceNatIp != null) {
        ipToReturn = PublicIp.createFromAddrAndVlan(sourceNatIp, _vlanDao.findById(sourceNatIp.getVlanId()));
    } else {
        ipToReturn = _ipAddrMgr.assignDedicateIpAddress(owner, null, vpc.getId(), dcId, true);
    }
    return ipToReturn;
}
Also used : PublicIp(com.cloud.network.addr.PublicIp) IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 64 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class ConfigurationManagerTest method runDedicatePublicIpRangeInvalidZone.

void runDedicatePublicIpRangeInvalidZone() throws Exception {
    TransactionLegacy txn = TransactionLegacy.open("runDedicatePublicIpRangeInvalidZone");
    when(configurationMgr._vlanDao.findById(anyLong())).thenReturn(vlan);
    when(configurationMgr._accountVlanMapDao.listAccountVlanMapsByVlan(anyLong())).thenReturn(null);
    // public ip range belongs to zone of type basic
    DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", null, null, NetworkType.Basic, null, null, true, true, null, null);
    when(configurationMgr._zoneDao.findById(anyLong())).thenReturn(dc);
    List<IPAddressVO> ipAddressList = new ArrayList<IPAddressVO>();
    IPAddressVO ipAddress = new IPAddressVO(new Ip("75.75.75.75"), 1, 0xaabbccddeeffL, 10, false);
    ipAddressList.add(ipAddress);
    when(configurationMgr._publicIpAddressDao.listByVlanId(anyLong())).thenReturn(ipAddressList);
    try {
        configurationMgr.dedicatePublicIpRange(dedicatePublicIpRangesCmd);
    } catch (Exception e) {
        Assert.assertTrue(e.getMessage().contains("Public IP range can be dedicated to an account only in the zone of type Advanced"));
    } finally {
        txn.close("runDedicatePublicIpRangeInvalidZone");
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) TransactionLegacy(com.cloud.utils.db.TransactionLegacy) Ip(com.cloud.utils.net.Ip) ArrayList(java.util.ArrayList) IPAddressVO(com.cloud.network.dao.IPAddressVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Example 65 with IPAddressVO

use of com.cloud.network.dao.IPAddressVO in project cloudstack by apache.

the class ConfigurationManagerTest method runDedicatePublicIpRangeDedicatedRange.

void runDedicatePublicIpRangeDedicatedRange() throws Exception {
    TransactionLegacy txn = TransactionLegacy.open("runDedicatePublicIpRangeDedicatedRange");
    when(configurationMgr._vlanDao.findById(anyLong())).thenReturn(vlan);
    // public ip range is already dedicated
    List<AccountVlanMapVO> accountVlanMaps = new ArrayList<AccountVlanMapVO>();
    AccountVlanMapVO accountVlanMap = new AccountVlanMapVO(1, 1);
    accountVlanMaps.add(accountVlanMap);
    when(configurationMgr._accountVlanMapDao.listAccountVlanMapsByVlan(anyLong())).thenReturn(accountVlanMaps);
    DataCenterVO dc = new DataCenterVO(UUID.randomUUID().toString(), "test", "8.8.8.8", null, "10.0.0.1", null, "10.0.0.1/24", null, null, NetworkType.Advanced, null, null, true, true, null, null);
    when(configurationMgr._zoneDao.findById(anyLong())).thenReturn(dc);
    List<IPAddressVO> ipAddressList = new ArrayList<IPAddressVO>();
    IPAddressVO ipAddress = new IPAddressVO(new Ip("75.75.75.75"), 1, 0xaabbccddeeffL, 10, false);
    ipAddressList.add(ipAddress);
    when(configurationMgr._publicIpAddressDao.listByVlanId(anyLong())).thenReturn(ipAddressList);
    try {
        configurationMgr.dedicatePublicIpRange(dedicatePublicIpRangesCmd);
    } catch (Exception e) {
        Assert.assertTrue(e.getMessage().contains("Public IP range has already been dedicated"));
    } finally {
        txn.close("runDedicatePublicIpRangePublicIpRangeDedicated");
    }
}
Also used : DataCenterVO(com.cloud.dc.DataCenterVO) TransactionLegacy(com.cloud.utils.db.TransactionLegacy) Ip(com.cloud.utils.net.Ip) ArrayList(java.util.ArrayList) AccountVlanMapVO(com.cloud.dc.AccountVlanMapVO) IPAddressVO(com.cloud.network.dao.IPAddressVO) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException)

Aggregations

IPAddressVO (com.cloud.network.dao.IPAddressVO)109 ArrayList (java.util.ArrayList)43 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)42 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)39 Account (com.cloud.user.Account)37 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)32 DB (com.cloud.utils.db.DB)28 TransactionStatus (com.cloud.utils.db.TransactionStatus)26 Network (com.cloud.network.Network)25 PublicIp (com.cloud.network.addr.PublicIp)22 DataCenter (com.cloud.dc.DataCenter)17 VlanVO (com.cloud.dc.VlanVO)16 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)16 List (java.util.List)15 TransactionCallbackNoReturn (com.cloud.utils.db.TransactionCallbackNoReturn)14 Ip (com.cloud.utils.net.Ip)14 NetworkOffering (com.cloud.offering.NetworkOffering)13 TransactionCallbackWithException (com.cloud.utils.db.TransactionCallbackWithException)13 ConcurrentOperationException (com.cloud.exception.ConcurrentOperationException)12 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)11