Search in sources :

Example 91 with IPAddressVO

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

the class FloatingIpModel method update.

@Override
public void update(ModelController controller) throws InternalErrorException, IOException {
    assert _initialized;
    ApiConnector api = controller.getApiAccessor();
    ContrailManager manager = controller.getManager();
    FloatingIp fip = _fip;
    if (_fip == null) {
        _fip = fip = (FloatingIp) controller.getApiAccessor().findById(FloatingIp.class, _uuid);
        if (fip == null) {
            fip = new FloatingIp();
            fip.setUuid(_uuid);
            fip.setAddress(_addr);
            fip.setName(_name);
            fip.setParent(_fipPoolModel.getFloatingIpPool());
        }
    }
    IPAddressVO ipAddrVO = controller.getIPAddressDao().findById(_id);
    assert ipAddrVO != null : "can not find address object in db";
    Long vmId = ipAddrVO.getAssociatedWithVmId();
    Long networkId = ipAddrVO.getAssociatedWithNetworkId();
    if (vmId == null || networkId == null) {
        s_logger.debug("Floating ip is not yet associated to either vm or network");
        return;
    }
    NicVO nic = controller.getNicDao().findByNtwkIdAndInstanceId(networkId, vmId);
    assert nic != null : "can not find nic for the given network and vm in db";
    VMInstanceVO vm = controller.getVmDao().findById(vmId);
    assert vm != null : "can not find vm in db";
    VirtualMachineModel vmModel = manager.getDatabase().lookupVirtualMachine(vm.getUuid());
    assert vmModel != null : "can not find vm model";
    VMInterfaceModel vmiModel = vmModel.getVMInterface(nic.getUuid());
    assert vmiModel != null && vmiModel.getVMInterface() != null : "can not find virtual machine interface";
    fip.setVirtualMachineInterface(vmiModel.getVMInterface());
    if (_fip == null) {
        try {
            api.create(fip);
        } catch (Exception ex) {
            s_logger.debug("floating ip create", ex);
            throw new CloudRuntimeException("Failed to create floating ip", ex);
        }
        _fip = fip;
    } else {
        try {
            api.update(fip);
        } catch (IOException ex) {
            s_logger.warn("floating ip update", ex);
            throw new CloudRuntimeException("Unable to update floating ip object", ex);
        }
    }
    addToVMInterface(vmiModel);
    for (ModelObject successor : successors()) {
        successor.update(controller);
    }
}
Also used : ApiConnector(net.juniper.contrail.api.ApiConnector) ContrailManager(org.apache.cloudstack.network.contrail.management.ContrailManager) VMInstanceVO(com.cloud.vm.VMInstanceVO) IOException(java.io.IOException) FloatingIp(net.juniper.contrail.api.types.FloatingIp) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) InternalErrorException(com.cloud.exception.InternalErrorException) IOException(java.io.IOException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) IPAddressVO(com.cloud.network.dao.IPAddressVO) NicVO(com.cloud.vm.NicVO)

Example 92 with IPAddressVO

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

the class NetworkProviderTest method floatingIpTest.

@Test
public void floatingIpTest() {
    Network network = lookupTestNetwork("test-fip-net");
    if (network == null) {
        network = createTestNetwork("test-fip-net");
    }
    UserVm vm = _server.createVM("test-fip-vm", network);
    try {
        IPAddressVO ip = createFloatingIp(network, vm);
        deleteFloatingIp(ip);
    } catch (Exception e) {
        fail("unable to create/delete floating ip");
    }
    _server.deleteVM(vm, network);
}
Also used : UserVm(com.cloud.uservm.UserVm) VirtualNetwork(net.juniper.contrail.api.types.VirtualNetwork) Network(com.cloud.network.Network) IPAddressVO(com.cloud.network.dao.IPAddressVO) CloudException(com.cloud.exception.CloudException) IOException(java.io.IOException) Test(org.junit.Test)

Example 93 with IPAddressVO

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

the class VpcManagerImpl method getExistingSourceNatInVpc.

protected IPAddressVO getExistingSourceNatInVpc(final long ownerId, final long vpcId) {
    final List<IPAddressVO> addrs = listPublicIpsAssignedToVpc(ownerId, true, vpcId);
    IPAddressVO sourceNatIp = null;
    if (addrs.isEmpty()) {
        return null;
    } else {
        // Account already has ip addresses
        for (final IPAddressVO addr : addrs) {
            if (addr.isSourceNat()) {
                sourceNatIp = addr;
                return sourceNatIp;
            }
        }
        assert sourceNatIp != null : "How do we get a bunch of ip addresses but none of them are source nat? " + "account=" + ownerId + "; vpcId=" + vpcId;
    }
    return sourceNatIp;
}
Also used : IPAddressVO(com.cloud.network.dao.IPAddressVO)

Example 94 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 95 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)

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