Search in sources :

Example 16 with PublicIpAddress

use of com.cloud.network.PublicIpAddress in project cosmic by MissionCriticalCloud.

the class NicPlugInOutRules method getNicsToChangeOnRouter.

private Pair<Map<String, PublicIpAddress>, Map<String, PublicIpAddress>> getNicsToChangeOnRouter(final NetworkTopologyVisitor visitor) {
    // 1) check which nics need to be plugged/unplugged and plug/unplug them
    final Map<String, PublicIpAddress> nicsToPlug = new HashMap<>();
    final Map<String, PublicIpAddress> nicsToUnplug = new HashMap<>();
    final VpcManager vpcMgr = visitor.getVirtualNetworkApplianceFactory().getVpcMgr();
    final NicDao nicDao = visitor.getVirtualNetworkApplianceFactory().getNicDao();
    // find out nics to unplug
    for (final PublicIpAddress ip : _ipAddresses) {
        final long publicNtwkId = ip.getNetworkId();
        // rules, release it on the backend
        if (!vpcMgr.isIpAllocatedToVpc(ip)) {
            ip.setState(IpAddress.State.Releasing);
        }
        if (ip.getState() == IpAddress.State.Releasing) {
            final Nic nic = nicDao.findByIp4AddressAndNetworkIdAndInstanceId(publicNtwkId, _router.getId(), ip.getAddress().addr());
            if (nic != null) {
                nicsToUnplug.put(ip.getVlanTag(), ip);
                s_logger.debug("Need to unplug the nic for ip=" + ip + "; vlan=" + ip.getVlanTag() + " in public network id =" + publicNtwkId);
            }
        }
    }
    // find out nics to plug
    for (final PublicIpAddress ip : _ipAddresses) {
        final URI broadcastUri = BroadcastDomainType.Vlan.toUri(ip.getVlanTag());
        final long publicNtwkId = ip.getNetworkId();
        // rules, release it on the backend
        if (!vpcMgr.isIpAllocatedToVpc(ip)) {
            ip.setState(IpAddress.State.Releasing);
        }
        if (ip.getState() == IpAddress.State.Allocated || ip.getState() == IpAddress.State.Allocating) {
            // nic has to be plugged only when there are no nics for this
            // vlan tag exist on VR
            final Nic nic = nicDao.findByNetworkIdInstanceIdAndBroadcastUri(publicNtwkId, _router.getId(), broadcastUri.toString());
            if (nic == null && nicsToPlug.get(ip.getVlanTag()) == null) {
                nicsToPlug.put(ip.getVlanTag(), ip);
                s_logger.debug("Need to plug the nic for ip=" + ip + "; vlan=" + ip.getVlanTag() + " in public network id =" + publicNtwkId);
            } else {
                final PublicIpAddress nicToUnplug = nicsToUnplug.get(ip.getVlanTag());
                if (nicToUnplug != null) {
                    final NicVO nicVO = nicDao.findByIp4AddressAndNetworkIdAndInstanceId(publicNtwkId, _router.getId(), nicToUnplug.getAddress().addr());
                    nicVO.setIPv4Address(ip.getAddress().addr());
                    nicDao.update(nicVO.getId(), nicVO);
                    s_logger.debug("Updated the nic " + nicVO + " with the new ip address " + ip.getAddress().addr());
                    nicsToUnplug.remove(ip.getVlanTag());
                }
            }
        }
    }
    final Pair<Map<String, PublicIpAddress>, Map<String, PublicIpAddress>> nicsToChange = new Pair<>(nicsToPlug, nicsToUnplug);
    return nicsToChange;
}
Also used : HashMap(java.util.HashMap) NicDao(com.cloud.vm.dao.NicDao) Nic(com.cloud.vm.Nic) URI(java.net.URI) PublicIpAddress(com.cloud.network.PublicIpAddress) VpcManager(com.cloud.network.vpc.VpcManager) NicVO(com.cloud.vm.NicVO) HashMap(java.util.HashMap) Map(java.util.Map) Pair(com.cloud.utils.Pair)

Example 17 with PublicIpAddress

use of com.cloud.network.PublicIpAddress in project cosmic by MissionCriticalCloud.

the class NiciraNvpElementTest method applyIpTest.

@Test
public void applyIpTest() throws ResourceUnavailableException {
    final Network network = mock(Network.class);
    when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch);
    when(network.getId()).thenReturn(NETWORK_ID);
    when(network.getPhysicalNetworkId()).thenReturn(NETWORK_ID);
    final NetworkOffering offering = mock(NetworkOffering.class);
    when(offering.getId()).thenReturn(NETWORK_ID);
    when(offering.getTrafficType()).thenReturn(TrafficType.Guest);
    when(offering.getGuestType()).thenReturn(GuestType.Isolated);
    final List<PublicIpAddress> ipAddresses = new ArrayList<>();
    final PublicIpAddress pipReleased = mock(PublicIpAddress.class);
    final PublicIpAddress pipAllocated = mock(PublicIpAddress.class);
    final Ip ipReleased = new Ip("42.10.10.10");
    final Ip ipAllocated = new Ip("10.10.10.10");
    when(pipAllocated.getState()).thenReturn(IpAddress.State.Allocated);
    when(pipAllocated.getAddress()).thenReturn(ipAllocated);
    when(pipAllocated.getNetmask()).thenReturn("255.255.255.0");
    when(pipReleased.getState()).thenReturn(IpAddress.State.Releasing);
    when(pipReleased.getAddress()).thenReturn(ipReleased);
    when(pipReleased.getNetmask()).thenReturn("255.255.255.0");
    ipAddresses.add(pipAllocated);
    ipAddresses.add(pipReleased);
    final Set<Service> services = new HashSet<>();
    services.add(Service.SourceNat);
    services.add(Service.StaticNat);
    services.add(Service.PortForwarding);
    final List<NiciraNvpDeviceVO> deviceList = new ArrayList<>();
    final NiciraNvpDeviceVO nndVO = mock(NiciraNvpDeviceVO.class);
    final NiciraNvpRouterMappingVO nnrmVO = mock(NiciraNvpRouterMappingVO.class);
    when(niciraNvpRouterMappingDao.findByNetworkId(NETWORK_ID)).thenReturn(nnrmVO);
    when(nnrmVO.getLogicalRouterUuid()).thenReturn("abcde");
    when(nndVO.getHostId()).thenReturn(NETWORK_ID);
    final HostVO hvo = mock(HostVO.class);
    when(hvo.getId()).thenReturn(NETWORK_ID);
    when(hvo.getDetail("l3gatewayserviceuuid")).thenReturn("abcde");
    when(hostDao.findById(NETWORK_ID)).thenReturn(hvo);
    deviceList.add(nndVO);
    when(niciraNvpDao.listByPhysicalNetwork(NETWORK_ID)).thenReturn(deviceList);
    final ConfigurePublicIpsOnLogicalRouterAnswer answer = mock(ConfigurePublicIpsOnLogicalRouterAnswer.class);
    when(answer.getResult()).thenReturn(true);
    when(agentManager.easySend(eq(NETWORK_ID), any(ConfigurePublicIpsOnLogicalRouterCommand.class))).thenReturn(answer);
    assertTrue(element.applyIps(network, ipAddresses, services));
    verify(agentManager, atLeast(1)).easySend(eq(NETWORK_ID), argThat(new ArgumentMatcher<ConfigurePublicIpsOnLogicalRouterCommand>() {

        @Override
        public boolean matches(final Object argument) {
            final ConfigurePublicIpsOnLogicalRouterCommand command = (ConfigurePublicIpsOnLogicalRouterCommand) argument;
            if (command.getPublicCidrs().size() == 1) {
                return true;
            }
            return false;
        }
    }));
}
Also used : NetworkOffering(com.cloud.offering.NetworkOffering) Ip(com.cloud.utils.net.Ip) NiciraNvpDeviceVO(com.cloud.network.NiciraNvpDeviceVO) ArrayList(java.util.ArrayList) NetworkOrchestrationService(com.cloud.engine.orchestration.service.NetworkOrchestrationService) Service(com.cloud.network.Network.Service) HostVO(com.cloud.host.HostVO) PublicIpAddress(com.cloud.network.PublicIpAddress) NiciraNvpRouterMappingVO(com.cloud.network.NiciraNvpRouterMappingVO) Network(com.cloud.network.Network) ArgumentMatcher(org.mockito.ArgumentMatcher) ConfigurePublicIpsOnLogicalRouterAnswer(com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer) ConfigurePublicIpsOnLogicalRouterCommand(com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 18 with PublicIpAddress

use of com.cloud.network.PublicIpAddress in project cosmic by MissionCriticalCloud.

the class NiciraNvpElement method applyIps.

/**
 * From interface IpDeployer
 *
 * @param network
 * @param ipAddress
 * @param services
 * @return
 * @throws ResourceUnavailableException
 */
@Override
public boolean applyIps(final Network network, final List<? extends PublicIpAddress> ipAddress, final Set<Network.Service> services) throws ResourceUnavailableException {
    if (services.contains(Network.Service.SourceNat)) {
        // Only if we need to provide SourceNat we need to configure the logical router
        // SourceNat is required for StaticNat and PortForwarding
        final List<NiciraNvpDeviceVO> devices = niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId());
        if (devices.isEmpty()) {
            s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId());
            return false;
        }
        final NiciraNvpDeviceVO niciraNvpDevice = devices.get(0);
        final HostVO niciraNvpHost = hostDao.findById(niciraNvpDevice.getHostId());
        hostDao.loadDetails(niciraNvpHost);
        final NiciraNvpRouterMappingVO routermapping = niciraNvpRouterMappingDao.findByNetworkId(network.getId());
        if (routermapping == null) {
            s_logger.error("No logical router uuid found for network " + network.getDisplayText());
            return false;
        }
        final List<String> cidrs = new ArrayList<>();
        for (final PublicIpAddress ip : ipAddress) {
            if (ip.getState() == IpAddress.State.Releasing) {
                // the Logical Router
                continue;
            }
            cidrs.add(ip.getAddress().addr() + "/" + NetUtils.getCidrSize(ip.getNetmask()));
        }
        final ConfigurePublicIpsOnLogicalRouterCommand cmd = new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), niciraNvpHost.getDetail("l3gatewayserviceuuid"), cidrs);
        final ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer) agentMgr.easySend(niciraNvpHost.getId(), cmd);
        // FIXME answer can be null if the host is down
        return answer.getResult();
    } else {
        s_logger.debug("No need to provision ip addresses as we are not providing L3 services.");
    }
    return true;
}
Also used : PublicIpAddress(com.cloud.network.PublicIpAddress) NiciraNvpRouterMappingVO(com.cloud.network.NiciraNvpRouterMappingVO) NiciraNvpDeviceVO(com.cloud.network.NiciraNvpDeviceVO) ArrayList(java.util.ArrayList) ConfigurePublicIpsOnLogicalRouterAnswer(com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer) HostVO(com.cloud.host.HostVO) ConfigurePublicIpsOnLogicalRouterCommand(com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand)

Example 19 with PublicIpAddress

use of com.cloud.network.PublicIpAddress 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();
    final PublicIpAddress ipAddr = _networkMgr.getPublicIpAddress(publicIpId);
    if (ipAddr == null) {
        throw new InvalidParameterValueException(String.format("Unable to create remote access VPN, invalid public IP address {\"id\": %s}.", 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);
    Long networkId = ipAddress.getAssociatedWithNetworkId();
    if (networkId != null) {
        _networkMgr.checkIpForService(ipAddress, Service.Vpn, null);
    }
    final Long vpcId = ipAddress.getVpcId();
    if (vpcId != null && ipAddress.isSourceNat()) {
        assert networkId == null;
        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 (vpnVO.getState() == RemoteAccessVpn.State.Added) {
            return vpnVO;
        }
        throw new InvalidParameterValueException(String.format("A remote Access VPN already exists for the public IP address [%s].", ipAddr.getAddress().toString()));
    }
    if (ipRange == null) {
        ipRange = RemoteAccessVpnClientIpRange.valueIn(ipAddr.getAccountId());
    }
    validateIpRange(ipRange, InvalidParameterValueException.class);
    String[] range = ipRange.split("-");
    Pair<String, Integer> cidr = null;
    if (networkId != null) {
        long ipAddressOwner = ipAddr.getAccountId();
        vpnVO = _remoteAccessVpnDao.findByAccountAndNetwork(ipAddressOwner, networkId);
        if (vpnVO != null) {
            if (vpnVO.getState() == RemoteAccessVpn.State.Added) {
                return vpnVO;
            }
            throw new InvalidParameterValueException(String.format("A remote access VPN already exists for the account [%s].", ipAddressOwner));
        }
        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 {
        Vpc vpc = _vpcDao.findById(vpcId);
        cidr = NetUtils.getCidr(vpc.getCidr());
    }
    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]);
    }
    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 20 with PublicIpAddress

use of com.cloud.network.PublicIpAddress in project cloudstack by apache.

the class RemoteAccessVpnManagerImpl method searchForRemoteAccessVpns.

@Override
public Pair<List<? extends RemoteAccessVpn>, Integer> searchForRemoteAccessVpns(ListRemoteAccessVpnsCmd cmd) {
    Account caller = CallContext.current().getCallingAccount();
    Long ipAddressId = cmd.getPublicIpId();
    List<Long> permittedAccounts = new ArrayList<>();
    Long vpnId = cmd.getId();
    Long networkId = cmd.getNetworkId();
    if (ipAddressId != null) {
        PublicIpAddress publicIp = _networkMgr.getPublicIpAddress(ipAddressId);
        if (publicIp == null) {
            throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddressId + " not found.");
        } else {
            Long ipAddrAcctId = publicIp.getAccountId();
            if (ipAddrAcctId == null) {
                throw new InvalidParameterValueException("Unable to list remote access vpns, IP address " + ipAddressId + " is not associated with an account.");
            }
        }
        _accountMgr.checkAccess(caller, null, true, publicIp);
    }
    Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<>(cmd.getDomainId(), cmd.isRecursive(), null);
    _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false);
    Long domainId = domainIdRecursiveListProject.first();
    Boolean isRecursive = domainIdRecursiveListProject.second();
    ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
    Filter filter = new Filter(RemoteAccessVpnVO.class, "serverAddressId", false, cmd.getStartIndex(), cmd.getPageSizeVal());
    SearchBuilder<RemoteAccessVpnVO> sb = _remoteAccessVpnDao.createSearchBuilder();
    _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sb.and("serverAddressId", sb.entity().getServerAddressId(), Op.EQ);
    sb.and("id", sb.entity().getId(), Op.EQ);
    sb.and("networkId", sb.entity().getNetworkId(), Op.EQ);
    sb.and("state", sb.entity().getState(), Op.EQ);
    sb.and("display", sb.entity().isDisplay(), Op.EQ);
    SearchCriteria<RemoteAccessVpnVO> sc = sb.create();
    _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
    sc.setParameters("state", RemoteAccessVpn.State.Running);
    if (ipAddressId != null) {
        sc.setParameters("serverAddressId", ipAddressId);
    }
    if (vpnId != null) {
        sc.setParameters("id", vpnId);
    }
    if (networkId != null) {
        sc.setParameters("networkId", networkId);
    }
    Pair<List<RemoteAccessVpnVO>, Integer> result = _remoteAccessVpnDao.searchAndCount(sc, filter);
    return new Pair<>(result.first(), result.second());
}
Also used : Account(com.cloud.user.Account) RemoteAccessVpnVO(com.cloud.network.dao.RemoteAccessVpnVO) Ternary(com.cloud.utils.Ternary) ArrayList(java.util.ArrayList) PublicIpAddress(com.cloud.network.PublicIpAddress) ListProjectResourcesCriteria(com.cloud.projects.Project.ListProjectResourcesCriteria) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Filter(com.cloud.utils.db.Filter) List(java.util.List) ArrayList(java.util.ArrayList) Pair(com.cloud.utils.Pair)

Aggregations

PublicIpAddress (com.cloud.network.PublicIpAddress)26 ArrayList (java.util.ArrayList)15 Network (com.cloud.network.Network)12 HashMap (java.util.HashMap)9 Map (java.util.Map)8 NicVO (com.cloud.vm.NicVO)7 IPAddressVO (com.cloud.network.dao.IPAddressVO)6 PublicIp (com.cloud.network.addr.PublicIp)5 Pair (com.cloud.utils.Pair)5 Ip (com.cloud.utils.net.Ip)5 Nic (com.cloud.vm.Nic)5 URI (java.net.URI)5 ConfigurePublicIpsOnLogicalRouterAnswer (com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterAnswer)4 ConfigurePublicIpsOnLogicalRouterCommand (com.cloud.agent.api.ConfigurePublicIpsOnLogicalRouterCommand)4 Commands (com.cloud.agent.manager.Commands)4 DataCenterVO (com.cloud.dc.DataCenterVO)4 NicDao (com.cloud.vm.dao.NicDao)4 HostVO (com.cloud.host.HostVO)3 NiciraNvpDeviceVO (com.cloud.network.NiciraNvpDeviceVO)3 NiciraNvpRouterMappingVO (com.cloud.network.NiciraNvpRouterMappingVO)3