Search in sources :

Example 1 with IpPort

use of org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.IpPort in project netvirt by opendaylight.

the class ExternalRoutersListener method update.

@Override
protected void update(InstanceIdentifier<Routers> identifier, Routers original, Routers update) {
    String routerName = original.getRouterName();
    Long routerId = NatUtil.getVpnId(dataBroker, routerName);
    if (routerId == NatConstants.INVALID_ID) {
        LOG.error("update : external router event - Invalid routerId for routerName {}", routerName);
        return;
    }
    // Check if its update on SNAT flag
    boolean originalSNATEnabled = original.isEnableSnat();
    boolean updatedSNATEnabled = update.isEnableSnat();
    LOG.debug("update :called with originalFlag and updatedFlag for SNAT enabled " + "as {} and {}", originalSNATEnabled, updatedSNATEnabled);
    if (natMode == NatMode.Conntrack && !upgradeState.isUpgradeInProgress()) {
        if (originalSNATEnabled != updatedSNATEnabled) {
            BigInteger primarySwitchId;
            if (originalSNATEnabled) {
                // SNAT disabled for the router
                centralizedSwitchScheduler.releaseCentralizedSwitch(update);
            } else {
                centralizedSwitchScheduler.scheduleCentralizedSwitch(update);
            }
        } else if (updatedSNATEnabled) {
            centralizedSwitchScheduler.updateCentralizedSwitch(original, update);
        }
        List<ExternalIps> originalExternalIps = original.getExternalIps();
        List<ExternalIps> updateExternalIps = update.getExternalIps();
        if (!Objects.equals(originalExternalIps, updateExternalIps)) {
            if (originalExternalIps == null || originalExternalIps.isEmpty()) {
                centralizedSwitchScheduler.scheduleCentralizedSwitch(update);
            }
        }
    } else {
        /* Get Primary Napt Switch for existing router from "router-to-napt-switch" DS.
             * if dpnId value is null or zero then go for electing new Napt switch for existing router.
             */
        long bgpVpnId = NatConstants.INVALID_ID;
        Uuid bgpVpnUuid = NatUtil.getVpnForRouter(dataBroker, routerName);
        if (bgpVpnUuid != null) {
            bgpVpnId = NatUtil.getVpnId(dataBroker, bgpVpnUuid.getValue());
        }
        BigInteger dpnId = getPrimaryNaptSwitch(routerName);
        if (dpnId == null || dpnId.equals(BigInteger.ZERO)) {
            // Router has no interface attached
            return;
        }
        final long finalBgpVpnId = bgpVpnId;
        coordinator.enqueueJob(NatConstants.NAT_DJC_PREFIX + update.getKey(), () -> {
            WriteTransaction writeFlowInvTx = dataBroker.newWriteOnlyTransaction();
            WriteTransaction removeFlowInvTx = dataBroker.newWriteOnlyTransaction();
            Uuid networkId = original.getNetworkId();
            if (originalSNATEnabled != updatedSNATEnabled) {
                if (originalSNATEnabled) {
                    // SNAT disabled for the router
                    Uuid networkUuid = original.getNetworkId();
                    LOG.info("update : SNAT disabled for Router {}", routerName);
                    Collection<String> externalIps = NatUtil.getExternalIpsForRouter(dataBroker, routerId);
                    handleDisableSnat(original, networkUuid, externalIps, false, null, dpnId, routerId, removeFlowInvTx);
                } else {
                    LOG.info("update : SNAT enabled for Router {}", original.getRouterName());
                    handleEnableSnat(original, routerId, dpnId, finalBgpVpnId, removeFlowInvTx);
                }
            }
            if (!Objects.equals(original.getExtGwMacAddress(), update.getExtGwMacAddress())) {
                NatUtil.installRouterGwFlows(dataBroker, vpnManager, original, dpnId, NwConstants.DEL_FLOW);
                NatUtil.installRouterGwFlows(dataBroker, vpnManager, update, dpnId, NwConstants.ADD_FLOW);
            }
            // Check if the Update is on External IPs
            LOG.debug("update : Checking if this is update on External IPs");
            List<String> originalExternalIps = NatUtil.getIpsListFromExternalIps(original.getExternalIps());
            List<String> updatedExternalIps = NatUtil.getIpsListFromExternalIps(update.getExternalIps());
            // Check if the External IPs are added during the update.
            Set<String> addedExternalIps = new HashSet<>(updatedExternalIps);
            addedExternalIps.removeAll(originalExternalIps);
            if (addedExternalIps.size() != 0) {
                LOG.debug("update : Start processing of the External IPs addition during the update operation");
                vpnManager.addArpResponderFlowsToExternalNetworkIps(routerName, addedExternalIps, update.getExtGwMacAddress(), dpnId, update.getNetworkId(), null);
                for (String addedExternalIp : addedExternalIps) {
                    /*
                        1) Do nothing in the IntExtIp model.
                        2) Initialise the count of the added external IP to 0 in the ExternalCounter model.
                     */
                    String[] externalIpParts = NatUtil.getExternalIpAndPrefix(addedExternalIp);
                    String externalIp = externalIpParts[0];
                    String externalIpPrefix = externalIpParts[1];
                    String externalpStr = externalIp + "/" + externalIpPrefix;
                    LOG.debug("update : Initialise the count mapping of the external IP {} for the " + "router ID {} in the ExternalIpsCounter model.", externalpStr, routerId);
                    naptManager.initialiseNewExternalIpCounter(routerId, externalpStr);
                }
                LOG.debug("update : End processing of the External IPs addition during the update operation");
            }
            // Check if the External IPs are removed during the update.
            Set<String> removedExternalIps = new HashSet<>(originalExternalIps);
            removedExternalIps.removeAll(updatedExternalIps);
            if (removedExternalIps.size() > 0) {
                LOG.debug("update : Start processing of the External IPs removal during the update operation");
                vpnManager.removeArpResponderFlowsToExternalNetworkIps(routerName, removedExternalIps, original.getExtGwMacAddress(), dpnId, networkId);
                for (String removedExternalIp : removedExternalIps) {
                    /*
                        1) Remove the mappings in the IntExt IP model which has external IP.
                        2) Remove the external IP in the ExternalCounter model.
                        3) For the corresponding subnet IDs whose external IP mapping was removed, allocate one of the
                           least loaded external IP.
                           Store the subnet IP and the reallocated external IP mapping in the IntExtIp model.
                        4) Increase the count of the allocated external IP by one.
                        5) Advertise to the BGP if external IP is allocated for the first time for the router
                         i.e. the route for the external IP is absent.
                        6) Remove the NAPT translation entries from Inbound and Outbound NAPT tables for
                         the removed external IPs and also from the model.
                        7) Advertise to the BGP for removing the route for the removed external IPs.
                     */
                    String[] externalIpParts = NatUtil.getExternalIpAndPrefix(removedExternalIp);
                    String externalIp = externalIpParts[0];
                    String externalIpPrefix = externalIpParts[1];
                    String externalIpAddrStr = externalIp + "/" + externalIpPrefix;
                    LOG.debug("update : Clear the routes from the BGP and remove the FIB and TS " + "entries for removed external IP {}", externalIpAddrStr);
                    Uuid vpnUuId = NatUtil.getVpnIdfromNetworkId(dataBroker, networkId);
                    String vpnName = "";
                    if (vpnUuId != null) {
                        vpnName = vpnUuId.getValue();
                    }
                    clrRtsFromBgpAndDelFibTs(dpnId, routerId, externalIpAddrStr, vpnName, networkId, update.getExtGwMacAddress(), removeFlowInvTx);
                    LOG.debug("update : Remove the mappings in the IntExtIP model which has external IP.");
                    // Get the internal IPs which are associated to the removed external IPs
                    List<IpMap> ipMaps = naptManager.getIpMapList(dataBroker, routerId);
                    List<String> removedInternalIps = new ArrayList<>();
                    for (IpMap ipMap : ipMaps) {
                        if (ipMap.getExternalIp().equals(externalIpAddrStr)) {
                            removedInternalIps.add(ipMap.getInternalIp());
                        }
                    }
                    LOG.debug("update : Remove the mappings of the internal IPs from the IntExtIP model.");
                    for (String removedInternalIp : removedInternalIps) {
                        LOG.debug("update : Remove the IP mapping of the internal IP {} for the " + "router ID {} from the IntExtIP model", removedInternalIp, routerId);
                        naptManager.removeFromIpMapDS(routerId, removedInternalIp);
                    }
                    LOG.debug("update : Remove the count mapping of the external IP {} for the " + "router ID {} from the ExternalIpsCounter model.", externalIpAddrStr, routerId);
                    naptManager.removeExternalIpCounter(routerId, externalIpAddrStr);
                    LOG.debug("update : Allocate the least loaded external IPs to the subnets " + "whose external IPs were removed.");
                    for (String removedInternalIp : removedInternalIps) {
                        allocateExternalIp(dpnId, update, routerId, routerName, networkId, removedInternalIp, writeFlowInvTx);
                    }
                    LOG.debug("update : Remove the NAPT translation entries from " + "Inbound and Outbound NAPT tables for the removed external IPs.");
                    // Get the internalIP and internal Port which were associated to the removed external IP.
                    List<Integer> externalPorts = new ArrayList<>();
                    Map<ProtocolTypes, List<String>> protoTypesIntIpPortsMap = new HashMap<>();
                    InstanceIdentifier<IpPortMapping> ipPortMappingId = InstanceIdentifier.builder(IntextIpPortMap.class).child(IpPortMapping.class, new IpPortMappingKey(routerId)).build();
                    Optional<IpPortMapping> ipPortMapping = MDSALUtil.read(dataBroker, LogicalDatastoreType.CONFIGURATION, ipPortMappingId);
                    if (ipPortMapping.isPresent()) {
                        List<IntextIpProtocolType> intextIpProtocolTypes = ipPortMapping.get().getIntextIpProtocolType();
                        for (IntextIpProtocolType intextIpProtocolType : intextIpProtocolTypes) {
                            ProtocolTypes protoType = intextIpProtocolType.getProtocol();
                            List<IpPortMap> ipPortMaps = intextIpProtocolType.getIpPortMap();
                            for (IpPortMap ipPortMap : ipPortMaps) {
                                IpPortExternal ipPortExternal = ipPortMap.getIpPortExternal();
                                if (ipPortExternal.getIpAddress().equals(externalIp)) {
                                    externalPorts.add(ipPortExternal.getPortNum());
                                    List<String> removedInternalIpPorts = protoTypesIntIpPortsMap.get(protoType);
                                    if (removedInternalIpPorts != null) {
                                        removedInternalIpPorts.add(ipPortMap.getIpPortInternal());
                                        protoTypesIntIpPortsMap.put(protoType, removedInternalIpPorts);
                                    } else {
                                        removedInternalIpPorts = new ArrayList<>();
                                        removedInternalIpPorts.add(ipPortMap.getIpPortInternal());
                                        protoTypesIntIpPortsMap.put(protoType, removedInternalIpPorts);
                                    }
                                }
                            }
                        }
                    }
                    // Remove the IP port map from the intext-ip-port-map model, which were containing
                    // the removed external IP.
                    Set<Map.Entry<ProtocolTypes, List<String>>> protoTypesIntIpPorts = protoTypesIntIpPortsMap.entrySet();
                    Map<String, List<String>> internalIpPortMap = new HashMap<>();
                    for (Map.Entry protoTypesIntIpPort : protoTypesIntIpPorts) {
                        ProtocolTypes protocolType = (ProtocolTypes) protoTypesIntIpPort.getKey();
                        List<String> removedInternalIpPorts = (List<String>) protoTypesIntIpPort.getValue();
                        for (String removedInternalIpPort : removedInternalIpPorts) {
                            // Remove the IP port map from the intext-ip-port-map model,
                            // which were containing the removed external IP
                            naptManager.removeFromIpPortMapDS(routerId, removedInternalIpPort, protocolType);
                            // Remove the IP port incomint packer map.
                            naptPacketInHandler.removeIncomingPacketMap(routerId + NatConstants.COLON_SEPARATOR + removedInternalIpPort);
                            String[] removedInternalIpPortParts = removedInternalIpPort.split(NatConstants.COLON_SEPARATOR);
                            if (removedInternalIpPortParts.length == 2) {
                                String removedInternalIp = removedInternalIpPortParts[0];
                                String removedInternalPort = removedInternalIpPortParts[1];
                                List<String> removedInternalPortsList = internalIpPortMap.get(removedInternalPort);
                                if (removedInternalPortsList != null) {
                                    removedInternalPortsList.add(removedInternalPort);
                                    internalIpPortMap.put(removedInternalIp, removedInternalPortsList);
                                } else {
                                    removedInternalPortsList = new ArrayList<>();
                                    removedInternalPortsList.add(removedInternalPort);
                                    internalIpPortMap.put(removedInternalIp, removedInternalPortsList);
                                }
                            }
                        }
                    }
                    // Delete the entry from SnatIntIpPortMap DS
                    Set<String> internalIps = internalIpPortMap.keySet();
                    for (String internalIp : internalIps) {
                        LOG.debug("update : Removing IpPort having the internal IP {} from the " + "model SnatIntIpPortMap", internalIp);
                        naptManager.removeFromSnatIpPortDS(routerId, internalIp);
                    }
                    naptManager.removeNaptPortPool(externalIp);
                    LOG.debug("update : Remove the NAPT translation entries from Inbound NAPT tables for the " + "removed external IP {}", externalIp);
                    for (Integer externalPort : externalPorts) {
                        // Remove the NAPT translation entries from Inbound NAPT table
                        naptEventHandler.removeNatFlows(dpnId, NwConstants.INBOUND_NAPT_TABLE, routerId, externalIp, externalPort);
                    }
                    Set<Map.Entry<String, List<String>>> internalIpPorts = internalIpPortMap.entrySet();
                    for (Map.Entry<String, List<String>> internalIpPort : internalIpPorts) {
                        String internalIp = internalIpPort.getKey();
                        LOG.debug("update : Remove the NAPT translation entries from Outbound NAPT tables for " + "the removed internal IP {}", internalIp);
                        List<String> internalPorts = internalIpPort.getValue();
                        for (String internalPort : internalPorts) {
                            // Remove the NAPT translation entries from Outbound NAPT table
                            naptPacketInHandler.removeIncomingPacketMap(routerId + NatConstants.COLON_SEPARATOR + internalIp + NatConstants.COLON_SEPARATOR + internalPort);
                            naptEventHandler.removeNatFlows(dpnId, NwConstants.OUTBOUND_NAPT_TABLE, routerId, internalIp, Integer.parseInt(internalPort));
                        }
                    }
                }
                LOG.debug("update : End processing of the External IPs removal during the update operation");
            }
            // Check if its Update on subnets
            LOG.debug("update : Checking if this is update on subnets");
            List<Uuid> originalSubnetIds = original.getSubnetIds();
            List<Uuid> updatedSubnetIds = update.getSubnetIds();
            Set<Uuid> addedSubnetIds = new HashSet<>(updatedSubnetIds);
            addedSubnetIds.removeAll(originalSubnetIds);
            // Check if the Subnet IDs are added during the update.
            if (addedSubnetIds.size() != 0) {
                LOG.debug("update : Start processing of the Subnet IDs addition during the update operation");
                for (Uuid addedSubnetId : addedSubnetIds) {
                    /*
                        1) Select the least loaded external IP for the subnet and store the mapping of the
                        subnet IP and the external IP in the IntExtIp model.
                        2) Increase the count of the selected external IP by one.
                        3) Advertise to the BGP if external IP is allocated for the first time for the
                        router i.e. the route for the external IP is absent.
                     */
                    String subnetIp = NatUtil.getSubnetIp(dataBroker, addedSubnetId);
                    if (subnetIp != null) {
                        allocateExternalIp(dpnId, update, routerId, routerName, networkId, subnetIp, writeFlowInvTx);
                    }
                }
                LOG.debug("update : End processing of the Subnet IDs addition during the update operation");
            }
            // Check if the Subnet IDs are removed during the update.
            Set<Uuid> removedSubnetIds = new HashSet<>(originalSubnetIds);
            removedSubnetIds.removeAll(updatedSubnetIds);
            List<ListenableFuture<Void>> futures = new ArrayList<>();
            if (removedSubnetIds.size() != 0) {
                LOG.debug("update : Start processing of the Subnet IDs removal during the update operation");
                for (Uuid removedSubnetId : removedSubnetIds) {
                    String[] subnetAddr = NatUtil.getSubnetIpAndPrefix(dataBroker, removedSubnetId);
                    if (subnetAddr != null) {
                        /*
                            1) Remove the subnet IP and the external IP in the IntExtIp map
                            2) Decrease the count of the coresponding external IP by one.
                            3) Advertise to the BGP for removing the routes of the corresponding external
                            IP if its not allocated to any other internal IP.
                        */
                        String externalIp = naptManager.getExternalIpAllocatedForSubnet(routerId, subnetAddr[0] + "/" + subnetAddr[1]);
                        if (externalIp == null) {
                            LOG.error("update : No mapping found for router ID {} and internal IP {}", routerId, subnetAddr[0]);
                            futures.add(NatUtil.waitForTransactionToComplete(writeFlowInvTx));
                            futures.add(NatUtil.waitForTransactionToComplete(removeFlowInvTx));
                            return futures;
                        }
                        naptManager.updateCounter(routerId, externalIp, false);
                        // used by any other internal ip in any router
                        if (!isExternalIpAllocated(externalIp)) {
                            LOG.debug("update : external ip is not allocated to any other " + "internal IP so proceeding to remove routes");
                            clrRtsFromBgpAndDelFibTs(dpnId, routerId, networkId, Collections.singleton(externalIp), null, update.getExtGwMacAddress(), removeFlowInvTx);
                            LOG.debug("update : Successfully removed fib entries in switch {} for " + "router {} with networkId {} and externalIp {}", dpnId, routerId, networkId, externalIp);
                        }
                        LOG.debug("update : Remove the IP mapping for the router ID {} and " + "internal IP {} external IP {}", routerId, subnetAddr[0], externalIp);
                        naptManager.removeIntExtIpMapDS(routerId, subnetAddr[0] + "/" + subnetAddr[1]);
                    }
                }
                LOG.debug("update : End processing of the Subnet IDs removal during the update operation");
            }
            futures.add(NatUtil.waitForTransactionToComplete(writeFlowInvTx));
            futures.add(NatUtil.waitForTransactionToComplete(removeFlowInvTx));
            return futures;
        }, NatConstants.NAT_DJC_MAX_RETRIES);
    }
// end of controller based SNAT
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IpPortMapping(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.IpPortMapping) ProtocolTypes(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ProtocolTypes) ArrayList(java.util.ArrayList) List(java.util.List) IpPortExternal(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.ip.port.map.IpPortExternal) HashSet(java.util.HashSet) WriteTransaction(org.opendaylight.controller.md.sal.binding.api.WriteTransaction) IpPortMappingKey(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.IpPortMappingKey) IpMap(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.map.ip.mapping.IpMap) ExternalIps(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ext.routers.routers.ExternalIps) BigInteger(java.math.BigInteger) Uuid(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid) IntextIpPortMap(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.IntextIpPortMap) IpPortMap(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.IpPortMap) IntextIpProtocolType(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.IntextIpProtocolType) BigInteger(java.math.BigInteger) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) IpMap(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.map.ip.mapping.IpMap) Map(java.util.Map) HashMap(java.util.HashMap) IntextIpPortMap(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.IntextIpPortMap) IpPortMap(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.IpPortMap)

Example 2 with IpPort

use of org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.IpPort in project netvirt by opendaylight.

the class InterfaceStateEventListener method removeSnatEntriesForPort.

// TODO Clean up the exception handling
@SuppressWarnings("checkstyle:IllegalCatch")
private void removeSnatEntriesForPort(String interfaceName, String routerName) {
    Long routerId = NatUtil.getVpnId(dataBroker, routerName);
    if (routerId == NatConstants.INVALID_ID) {
        LOG.error("removeSnatEntriesForPort : routerId not found for routername {}", routerName);
        return;
    }
    BigInteger naptSwitch = getNaptSwitchforRouter(dataBroker, routerName);
    if (naptSwitch == null || naptSwitch.equals(BigInteger.ZERO)) {
        LOG.error("removeSnatEntriesForPort : NaptSwitch is not elected for router {} with Id {}", routerName, routerId);
        return;
    }
    // getInternalIp for port
    List<String> fixedIps = getFixedIpsForPort(interfaceName);
    if (fixedIps == null) {
        LOG.warn("removeSnatEntriesForPort : Internal Ips not found for InterfaceName {} in router {} with id {}", interfaceName, routerName, routerId);
        return;
    }
    for (String internalIp : fixedIps) {
        LOG.debug("removeSnatEntriesForPort : Internal Ip retrieved for interface {} is {} in router with Id {}", interfaceName, internalIp, routerId);
        IpPort ipPort = NatUtil.getInternalIpPortInfo(dataBroker, routerId, internalIp);
        if (ipPort == null) {
            LOG.debug("removeSnatEntriesForPort : no snatint-ip-port-map found for ip:{}", internalIp);
            continue;
        }
        for (IntIpProtoType protoType : ipPort.getIntIpProtoType()) {
            ProtocolTypes protocol = protoType.getProtocol();
            for (Integer portnum : protoType.getPorts()) {
                // build and remove the flow in outbound table
                try {
                    removeNatFlow(naptSwitch, NwConstants.OUTBOUND_NAPT_TABLE, routerId, internalIp, portnum);
                } catch (Exception ex) {
                    LOG.error("removeSnatEntriesForPort : Failed to remove snat flow for internalIP {} with " + "Port {} protocol {} for routerId {} in OUTBOUNDTABLE of NaptSwitch {}", internalIp, portnum, protocol, routerId, naptSwitch, ex);
                }
                // Get the external IP address and the port from the model
                NAPTEntryEvent.Protocol proto = protocol.toString().equals(ProtocolTypes.TCP.toString()) ? NAPTEntryEvent.Protocol.TCP : NAPTEntryEvent.Protocol.UDP;
                IpPortExternal ipPortExternal = NatUtil.getExternalIpPortMap(dataBroker, routerId, internalIp, String.valueOf(portnum), proto);
                if (ipPortExternal == null) {
                    LOG.error("removeSnatEntriesForPort : Mapping for internalIp {} with port {} is not found in " + "router with Id {}", internalIp, portnum, routerId);
                    return;
                }
                String externalIpAddress = ipPortExternal.getIpAddress();
                Integer portNumber = ipPortExternal.getPortNum();
                // build and remove the flow in inboundtable
                try {
                    removeNatFlow(naptSwitch, NwConstants.INBOUND_NAPT_TABLE, routerId, externalIpAddress, portNumber);
                } catch (Exception ex) {
                    LOG.error("removeSnatEntriesForPort : Failed to remove snat flow internalIP {} with " + "Port {} protocol {} for routerId {} in INBOUNDTABLE of naptSwitch {}", externalIpAddress, portNumber, protocol, routerId, naptSwitch, ex);
                }
                String internalIpPort = internalIp + ":" + portnum;
                // delete the entry from IntExtIpPortMap DS
                try {
                    naptManager.removeFromIpPortMapDS(routerId, internalIpPort, proto);
                    naptManager.removePortFromPool(internalIpPort, externalIpAddress);
                } catch (Exception ex) {
                    LOG.error("removeSnatEntriesForPort : releaseIpExtPortMapping failed, Removal of " + "ipportmap {} for router {} failed", internalIpPort, routerId, ex);
                }
            }
        }
        // delete the entry from SnatIntIpPortMap DS
        LOG.debug("removeSnatEntriesForPort : Removing InternalIp:{} on router {}", internalIp, routerId);
        naptManager.removeFromSnatIpPortDS(routerId, internalIp);
    }
}
Also used : BigInteger(java.math.BigInteger) ProtocolTypes(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ProtocolTypes) BigInteger(java.math.BigInteger) IntIpProtoType(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.ip.port.IntIpProtoType) IpPort(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.IpPort) IpPortExternal(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.ip.port.map.IpPortExternal) ExecutionException(java.util.concurrent.ExecutionException)

Example 3 with IpPort

use of org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.IpPort in project netvirt by opendaylight.

the class NaptManager method removeFromSnatIpPortDS.

protected void removeFromSnatIpPortDS(long segmentId, String internalIp) {
    InstanceIdentifier<IpPort> intIp = InstanceIdentifier.builder(SnatintIpPortMap.class).child(IntipPortMap.class, new IntipPortMapKey(segmentId)).child(IpPort.class, new IpPortKey(internalIp)).build();
    // remove from SnatIpPortDS
    LOG.debug("removeFromSnatIpPortDS : Removing SnatIpPort from datastore : {}", intIp);
    MDSALUtil.syncDelete(dataBroker, LogicalDatastoreType.CONFIGURATION, intIp);
}
Also used : SnatintIpPortMap(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.SnatintIpPortMap) IpPortKey(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.IpPortKey) IpPort(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.IpPort) IntipPortMapKey(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.IntipPortMapKey)

Example 4 with IpPort

use of org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.IpPort in project netvirt by opendaylight.

the class NaptManager method getExternalAddressMapping.

/**
 * method to get external ip/port mapping when provided with internal ip/port pair
 * If already a mapping exist for the given input, then the existing mapping is returned
 * instead of overwriting with new ip/port pair.
 *
 * @param segmentId     - Router ID
 * @param sourceAddress - internal ip address/port pair
 * @param protocol      - TCP/UDP
 * @return external ip address/port
 */
// TODO Clean up the exception handling
@SuppressWarnings("checkstyle:IllegalCatch")
public SessionAddress getExternalAddressMapping(long segmentId, SessionAddress sourceAddress, NAPTEntryEvent.Protocol protocol) {
    LOG.debug("getExternalAddressMapping : called with segmentId {}, internalIp {} and port {}", segmentId, sourceAddress.getIpAddress(), sourceAddress.getPortNumber());
    /*
         1. Get Internal IP, Port in IP:Port format
         2. Inside DB with routerId get the list of entries and check if it matches with existing IP:Port
         3. If True return SessionAddress of ExternalIp and Port
         4. Else check ip Map and Form the ExternalIp and Port and update DB and then return ExternalIp and Port
         */
    // SessionAddress externalIpPort = new SessionAddress();
    String internalIpPort = sourceAddress.getIpAddress() + ":" + sourceAddress.getPortNumber();
    // First check existing Port Map.
    SessionAddress existingIpPort = checkIpPortMap(segmentId, internalIpPort, protocol);
    if (existingIpPort != null) {
        // populate externalIpPort from IpPortMap and return
        LOG.debug("getExternalAddressMapping : successfully returning existingIpPort as {} and {}", existingIpPort.getIpAddress(), existingIpPort.getPortNumber());
        return existingIpPort;
    } else {
        // Now check in ip-map
        String externalIp = checkIpMap(segmentId, sourceAddress.getIpAddress());
        if (externalIp == null) {
            LOG.error("getExternalAddressMapping : Unexpected error, internal to external " + "ip map does not exist");
            return null;
        } else {
            /* Logic assuming internalIp is always ip and not subnet
                  * case 1: externalIp is ip
                  *        a) goto externalIp pool and getPort and return
                  *        b) else return error
                  * case 2: externalIp is subnet
                  *        a) Take first externalIp and goto that Pool and getPort
                  *             if port -> return
                  *             else Take second externalIp and create that Pool and getPort
                  *             if port ->return
                  *             else
                  *             Continue same with third externalIp till we exhaust subnet
                  *        b) Nothing worked return error
                  */
            SubnetUtils externalIpSubnet;
            List<String> allIps = new ArrayList<>();
            String subnetPrefix = "/" + String.valueOf(NatConstants.DEFAULT_PREFIX);
            boolean extSubnetFlag = false;
            if (!externalIp.contains(subnetPrefix)) {
                extSubnetFlag = true;
                externalIpSubnet = new SubnetUtils(externalIp);
                allIps = Arrays.asList(externalIpSubnet.getInfo().getAllAddresses());
                LOG.debug("getExternalAddressMapping : total count of externalIps available {}", externalIpSubnet.getInfo().getAddressCount());
            } else {
                LOG.debug("getExternalAddressMapping : getExternalAddress single ip case");
                if (externalIp.contains(subnetPrefix)) {
                    // remove /32 what we got from checkIpMap
                    externalIp = externalIp.substring(0, externalIp.indexOf(subnetPrefix));
                }
                allIps.add(externalIp);
            }
            boolean nextExtIpFlag = false;
            for (String extIp : allIps) {
                LOG.info("getExternalAddressMapping : Looping externalIPs with externalIP now as {}", extIp);
                if (nextExtIpFlag) {
                    createNaptPortPool(extIp);
                    LOG.debug("getExternalAddressMapping : Created Pool for next Ext IP {}", extIp);
                }
                AllocateIdInput getIdInput = new AllocateIdInputBuilder().setPoolName(extIp).setIdKey(internalIpPort).build();
                try {
                    Future<RpcResult<AllocateIdOutput>> result = idManager.allocateId(getIdInput);
                    RpcResult<AllocateIdOutput> rpcResult;
                    if (result != null && result.get().isSuccessful()) {
                        LOG.debug("getExternalAddressMapping : Got id from idManager");
                        rpcResult = result.get();
                    } else {
                        LOG.error("getExternalAddressMapping : getExternalAddressMapping, idManager could not " + "allocate id retry if subnet");
                        if (!extSubnetFlag) {
                            LOG.error("getExternalAddressMapping : getExternalAddressMapping returning null " + "for single IP case, may be ports exhausted");
                            return null;
                        }
                        LOG.debug("getExternalAddressMapping : Could be ports exhausted case, " + "try with another externalIP if possible");
                        nextExtIpFlag = true;
                        continue;
                    }
                    int extPort = rpcResult.getResult().getIdValue().intValue();
                    // Write to ip-port-map before returning
                    IpPortExternalBuilder ipExt = new IpPortExternalBuilder();
                    IpPortExternal ipPortExt = ipExt.setIpAddress(extIp).setPortNum(extPort).build();
                    IpPortMap ipm = new IpPortMapBuilder().setKey(new IpPortMapKey(internalIpPort)).setIpPortInternal(internalIpPort).setIpPortExternal(ipPortExt).build();
                    LOG.debug("getExternalAddressMapping : writing into ip-port-map with " + "externalIP {} and port {}", ipPortExt.getIpAddress(), ipPortExt.getPortNum());
                    try {
                        MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION, getIpPortMapIdentifier(segmentId, internalIpPort, protocol), ipm);
                    } catch (UncheckedExecutionException uee) {
                        LOG.error("getExternalAddressMapping : Failed to write into ip-port-map with exception", uee);
                    }
                    // Write to snat-internal-ip-port-info
                    String internalIpAddress = sourceAddress.getIpAddress();
                    int ipPort = sourceAddress.getPortNumber();
                    ProtocolTypes protocolType = NatUtil.getProtocolType(protocol);
                    List<Integer> portList = new ArrayList<>(NatUtil.getInternalIpPortListInfo(dataBroker, segmentId, internalIpAddress, protocolType));
                    portList.add(ipPort);
                    IntIpProtoTypeBuilder builder = new IntIpProtoTypeBuilder();
                    IntIpProtoType intIpProtocolType = builder.setKey(new IntIpProtoTypeKey(protocolType)).setPorts(portList).build();
                    try {
                        MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.CONFIGURATION, NatUtil.buildSnatIntIpPortIdentifier(segmentId, internalIpAddress, protocolType), intIpProtocolType);
                    } catch (Exception ex) {
                        LOG.error("getExternalAddressMapping : Failed to write into snat-internal-ip-port-info " + "with exception", ex);
                    }
                    SessionAddress externalIpPort = new SessionAddress(extIp, extPort);
                    LOG.debug("getExternalAddressMapping : successfully returning externalIP {} " + "and port {}", externalIpPort.getIpAddress(), externalIpPort.getPortNumber());
                    return externalIpPort;
                } catch (InterruptedException | ExecutionException e) {
                    LOG.error("getExternalAddressMapping : Exception caught", e);
                    return null;
                }
            }
        // end of for loop
        }
    // end of else ipmap present
    }
    // end of else check ipmap
    LOG.error("getExternalAddressMapping : Unable to handle external IP address and port mapping with segmentId {}," + "internalIp {} and internalPort {}", segmentId, sourceAddress.getIpAddress(), sourceAddress.getPortNumber());
    return null;
}
Also used : ArrayList(java.util.ArrayList) IntIpProtoTypeBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.ip.port.IntIpProtoTypeBuilder) AllocateIdOutput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdOutput) IpPortExternalBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.ip.port.map.IpPortExternalBuilder) IpPortMapBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.IpPortMapBuilder) ProtocolTypes(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ProtocolTypes) IntIpProtoType(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.ip.port.IntIpProtoType) IpPortExternal(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.ip.port.map.IpPortExternal) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) IntIpProtoTypeKey(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.ip.port.IntIpProtoTypeKey) SubnetUtils(org.apache.commons.net.util.SubnetUtils) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) AllocateIdInput(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInput) RpcResult(org.opendaylight.yangtools.yang.common.RpcResult) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) AllocateIdInputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.AllocateIdInputBuilder) SnatintIpPortMap(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.SnatintIpPortMap) IntextIpPortMap(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.IntextIpPortMap) IpPortMap(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.IpPortMap) IpPortMapKey(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.IpPortMapKey)

Example 5 with IpPort

use of org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.IpPort in project netvirt by opendaylight.

the class NaptSwitchHA method removeSnatFlowsInOldNaptSwitch.

/* This method checks the switch that gone down is a NaptSwitch for a router.
       If it is a NaptSwitch
          1) selects new NAPT switch
          2) installs nat flows in new NAPT switch
          table 21(FIB)->26(PSNAT)->group(resubmit/napttunnel)->36(Terminating)->46(outbound)->47(resubmit)->21
          3) modify the group and miss entry flow in other vSwitches pointing to newNaptSwitch
          4) Remove nat flows in oldNaptSwitch
     */
/*public void handleNaptSwitchDown(BigInteger dpnId){

        LOG.debug("handleNaptSwitchDown method is called with dpnId {}",dpnId);
        BigInteger naptSwitch;
        try {
            NaptSwitches naptSwitches = NatUtil.getNaptSwitch(dataBroker);
            if (naptSwitches == null || naptSwitches.getRouterToNaptSwitch() == null
             || naptSwitches.getRouterToNaptSwitch().isEmpty()) {
                LOG.debug("NaptSwitchDown: NaptSwitch is not allocated for none of the routers");
                return;
            }
            for (RouterToNaptSwitch routerToNaptSwitch : naptSwitches.getRouterToNaptSwitch()) {
                String routerName = routerToNaptSwitch.getRouterName();
                naptSwitch = routerToNaptSwitch.getPrimarySwitchId();
                boolean naptStatus = isNaptSwitchDown(routerName,dpnId,naptSwitch);
                if (!naptStatus) {
                    LOG.debug("NaptSwitchDown: Switch with DpnId {} is not naptSwitch for router {}",
                            dpnId, routerName);
                } else {
                    removeSnatFlowsInOldNaptSwitch(routerName,naptSwitch);
                    return;
                }
            }
        } catch (Exception ex) {
            LOG.error("Exception in handleNaptSwitchDown method {}",ex);
        }
    }*/
protected void removeSnatFlowsInOldNaptSwitch(String routerName, Long routerId, BigInteger naptSwitch, Map<String, Long> externalIpmap, WriteTransaction removeFlowInvTx) {
    // remove SNAT flows in old NAPT SWITCH
    Uuid networkId = NatUtil.getNetworkIdFromRouterName(dataBroker, routerName);
    String vpnName = getExtNetworkVpnName(routerName, networkId);
    if (vpnName == null) {
        LOG.error("removeSnatFlowsInOldNaptSwitch : Vpn is not associated to externalN/w of router {}", routerName);
        return;
    }
    ProviderTypes extNwProvType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName, networkId);
    if (extNwProvType == null) {
        LOG.error("removeSnatFlowsInOldNaptSwitch : Unable to retrieve the External Network Provider Type " + "for Router {}", routerName);
        return;
    }
    if (extNwProvType == ProviderTypes.VXLAN) {
        evpnNaptSwitchHA.evpnRemoveSnatFlowsInOldNaptSwitch(routerName, routerId, vpnName, naptSwitch, removeFlowInvTx);
    } else {
        // Remove the Terminating Service table entry which forwards the packet to Outbound NAPT Table
        long tunnelId = NatUtil.getTunnelIdForNonNaptToNaptFlow(dataBroker, elanManager, idManager, routerId, routerName);
        String tsFlowRef = externalRouterListener.getFlowRefTs(naptSwitch, NwConstants.INTERNAL_TUNNEL_TABLE, tunnelId);
        FlowEntity tsNatFlowEntity = NatUtil.buildFlowEntity(naptSwitch, NwConstants.INTERNAL_TUNNEL_TABLE, tsFlowRef);
        LOG.info("removeSnatFlowsInOldNaptSwitch : Remove the flow in table {} for the old napt switch " + "with the DPN ID {} and router ID {}", NwConstants.INTERNAL_TUNNEL_TABLE, naptSwitch, routerId);
        mdsalManager.removeFlowToTx(tsNatFlowEntity, removeFlowInvTx);
    }
    if (NatUtil.isOpenStackVniSemanticsEnforcedForGreAndVxlan(elanManager, extNwProvType)) {
        // Remove the flow table 25->44 If there is no FIP Match on table 25 (PDNAT_TABLE)
        NatUtil.removePreDnatToSnatTableEntry(mdsalManager, naptSwitch, removeFlowInvTx);
    }
    // Remove the Outbound flow entry which forwards the packet to Outbound NAPT Table
    String outboundNatFlowRef = externalRouterListener.getFlowRefOutbound(naptSwitch, NwConstants.OUTBOUND_NAPT_TABLE, routerId);
    FlowEntity outboundNatFlowEntity = NatUtil.buildFlowEntity(naptSwitch, NwConstants.OUTBOUND_NAPT_TABLE, outboundNatFlowRef);
    LOG.info("Remove the flow in table {} for the old napt switch with the DPN ID {} and router ID {}", NwConstants.OUTBOUND_NAPT_TABLE, naptSwitch, routerId);
    mdsalManager.removeFlowToTx(outboundNatFlowEntity, removeFlowInvTx);
    // Remove the NAPT PFIB TABLE (47->21) which forwards the incoming packet to FIB Table matching on the
    // External Subnet Vpn Id.
    Collection<Uuid> externalSubnetIdsForRouter = NatUtil.getExternalSubnetIdsForRouter(dataBroker, routerName);
    for (Uuid externalSubnetId : externalSubnetIdsForRouter) {
        long subnetVpnId = NatUtil.getVpnId(dataBroker, externalSubnetId.getValue());
        if (subnetVpnId != -1) {
            String natPfibSubnetFlowRef = externalRouterListener.getFlowRefTs(naptSwitch, NwConstants.NAPT_PFIB_TABLE, subnetVpnId);
            FlowEntity natPfibFlowEntity = NatUtil.buildFlowEntity(naptSwitch, NwConstants.NAPT_PFIB_TABLE, natPfibSubnetFlowRef);
            mdsalManager.removeFlowToTx(natPfibFlowEntity, removeFlowInvTx);
            LOG.debug("removeSnatFlowsInOldNaptSwitch : Removed the flow in table {} with external subnet " + "Vpn Id {} as metadata on Napt Switch {}", NwConstants.NAPT_PFIB_TABLE, subnetVpnId, naptSwitch);
        }
    }
    // Remove the NAPT_PFIB_TABLE(47) flow entry forwards the packet to Fib Table for inbound traffic
    // matching on the router ID.
    String naptPFibflowRef = externalRouterListener.getFlowRefTs(naptSwitch, NwConstants.NAPT_PFIB_TABLE, routerId);
    FlowEntity naptPFibFlowEntity = NatUtil.buildFlowEntity(naptSwitch, NwConstants.NAPT_PFIB_TABLE, naptPFibflowRef);
    LOG.info("removeSnatFlowsInOldNaptSwitch : Remove the flow in table {} for the old napt switch " + "with the DPN ID {} and router ID {}", NwConstants.NAPT_PFIB_TABLE, naptSwitch, routerId);
    mdsalManager.removeFlowToTx(naptPFibFlowEntity, removeFlowInvTx);
    // Remove the NAPT_PFIB_TABLE(47) flow entry forwards the packet to Fib Table for outbound traffic
    // matching on the vpn ID.
    boolean switchSharedByRouters = false;
    Uuid extNetworkId = NatUtil.getNetworkIdFromRouterName(dataBroker, routerName);
    if (extNetworkId != null) {
        List<String> routerNamesAssociated = getRouterIdsForExtNetwork(extNetworkId);
        for (String routerNameAssociated : routerNamesAssociated) {
            if (!routerNameAssociated.equals(routerName)) {
                Long routerIdAssociated = NatUtil.getVpnId(dataBroker, routerNameAssociated);
                BigInteger naptDpn = NatUtil.getPrimaryNaptfromRouterName(dataBroker, routerNameAssociated);
                if (naptDpn != null && naptDpn.equals(naptSwitch)) {
                    LOG.debug("removeSnatFlowsInOldNaptSwitch : Napt switch {} is also acting as primary " + "for router {}", naptSwitch, routerIdAssociated);
                    switchSharedByRouters = true;
                    break;
                }
            }
        }
        if (!switchSharedByRouters) {
            Long vpnId = getVpnIdForRouter(routerId, extNetworkId);
            if (vpnId != NatConstants.INVALID_ID) {
                String naptFibflowRef = externalRouterListener.getFlowRefTs(naptSwitch, NwConstants.NAPT_PFIB_TABLE, vpnId);
                FlowEntity naptFibFlowEntity = NatUtil.buildFlowEntity(naptSwitch, NwConstants.NAPT_PFIB_TABLE, naptFibflowRef);
                LOG.info("removeSnatFlowsInOldNaptSwitch : Remove the flow in table {} for the old napt switch" + " with the DPN ID {} and vpnId {}", NwConstants.NAPT_PFIB_TABLE, naptSwitch, vpnId);
                mdsalManager.removeFlowToTx(naptFibFlowEntity, removeFlowInvTx);
            } else {
                LOG.error("removeSnatFlowsInOldNaptSwitch : Invalid vpnId retrieved for routerId {}", routerId);
                return;
            }
        }
    }
    // Remove Fib entries,tables 20->44 ,36-> 44
    String gwMacAddress = NatUtil.getExtGwMacAddFromRouterName(dataBroker, routerName);
    if (externalIpmap != null && !externalIpmap.isEmpty()) {
        for (Entry<String, Long> entry : externalIpmap.entrySet()) {
            String externalIp = entry.getKey();
            Long label = entry.getValue();
            externalRouterListener.delFibTsAndReverseTraffic(naptSwitch, routerId, externalIp, vpnName, extNetworkId, label, gwMacAddress, true, removeFlowInvTx);
            LOG.debug("removeSnatFlowsInOldNaptSwitch : Successfully removed fib entries in old naptswitch {} " + "for router {} and externalIps {} label {}", naptSwitch, routerId, externalIp, label);
        }
    } else {
        List<String> externalIps = NatUtil.getExternalIpsForRouter(dataBroker, routerName);
        if (networkId != null) {
            externalRouterListener.clearFibTsAndReverseTraffic(naptSwitch, routerId, networkId, externalIps, null, gwMacAddress, removeFlowInvTx);
            LOG.debug("removeSnatFlowsInOldNaptSwitch : Successfully removed fib entries in old naptswitch {} for " + "router {} with networkId {} and externalIps {}", naptSwitch, routerId, networkId, externalIps);
        } else {
            LOG.debug("removeSnatFlowsInOldNaptSwitch : External network not associated to router {}", routerId);
        }
        externalRouterListener.removeNaptFibExternalOutputFlows(routerId, naptSwitch, extNetworkId, externalIps, removeFlowInvTx);
    }
    // For the router ID get the internal IP , internal port and the corresponding external IP and external Port.
    IpPortMapping ipPortMapping = NatUtil.getIportMapping(dataBroker, routerId);
    if (ipPortMapping == null || ipPortMapping.getIntextIpProtocolType() == null || ipPortMapping.getIntextIpProtocolType().isEmpty()) {
        LOG.warn("removeSnatFlowsInOldNaptSwitch : No Internal Ip Port mapping associated to router {}, " + "no flows need to be removed in oldNaptSwitch {}", routerId, naptSwitch);
        return;
    }
    BigInteger cookieSnatFlow = NatUtil.getCookieNaptFlow(routerId);
    List<IntextIpProtocolType> intextIpProtocolTypes = ipPortMapping.getIntextIpProtocolType();
    for (IntextIpProtocolType intextIpProtocolType : intextIpProtocolTypes) {
        if (intextIpProtocolType.getIpPortMap() == null || intextIpProtocolType.getIpPortMap().isEmpty()) {
            LOG.debug("removeSnatFlowsInOldNaptSwitch : No {} session associated to router {}," + "no flows need to be removed in oldNaptSwitch {}", intextIpProtocolType.getProtocol(), routerId, naptSwitch);
            break;
        }
        List<IpPortMap> ipPortMaps = intextIpProtocolType.getIpPortMap();
        for (IpPortMap ipPortMap : ipPortMaps) {
            String ipPortInternal = ipPortMap.getIpPortInternal();
            String[] ipPortParts = ipPortInternal.split(":");
            if (ipPortParts.length != 2) {
                LOG.error("removeSnatFlowsInOldNaptSwitch : Unable to retrieve the Internal IP and port");
                continue;
            }
            String internalIp = ipPortParts[0];
            String internalPort = ipPortParts[1];
            // Build and remove flow in outbound NAPT table
            String switchFlowRef = NatUtil.getNaptFlowRef(naptSwitch, NwConstants.OUTBOUND_NAPT_TABLE, String.valueOf(routerId), internalIp, Integer.parseInt(internalPort));
            FlowEntity outboundNaptFlowEntity = NatUtil.buildFlowEntity(naptSwitch, NwConstants.OUTBOUND_NAPT_TABLE, cookieSnatFlow, switchFlowRef);
            LOG.info("removeSnatFlowsInOldNaptSwitch : Remove the flow in table {} for old napt switch " + "with the DPN ID {} and router ID {}", NwConstants.OUTBOUND_NAPT_TABLE, naptSwitch, routerId);
            mdsalManager.removeFlowToTx(outboundNaptFlowEntity, removeFlowInvTx);
            IpPortExternal ipPortExternal = ipPortMap.getIpPortExternal();
            if (ipPortExternal == null) {
                LOG.debug("removeSnatFlowsInOldNaptSwitch : External Ipport mapping not found for internalIp {} " + "with port {} for router {}", internalIp, internalPort, routerId);
                continue;
            }
            String externalIp = ipPortExternal.getIpAddress();
            int externalPort = ipPortExternal.getPortNum();
            // Build and remove flow in  inbound NAPT table
            switchFlowRef = NatUtil.getNaptFlowRef(naptSwitch, NwConstants.INBOUND_NAPT_TABLE, String.valueOf(routerId), externalIp, externalPort);
            FlowEntity inboundNaptFlowEntity = NatUtil.buildFlowEntity(naptSwitch, NwConstants.INBOUND_NAPT_TABLE, cookieSnatFlow, switchFlowRef);
            LOG.info("removeSnatFlowsInOldNaptSwitch : Remove the flow in table {} for old napt switch with the " + "DPN ID {} and router ID {}", NwConstants.INBOUND_NAPT_TABLE, naptSwitch, routerId);
            mdsalManager.removeFlowToTx(inboundNaptFlowEntity, removeFlowInvTx);
        }
    }
}
Also used : ProviderTypes(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ProviderTypes) IpPortMapping(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.IpPortMapping) FlowEntity(org.opendaylight.genius.mdsalutil.FlowEntity) Uuid(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid) IpPortMap(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.IpPortMap) IntextIpProtocolType(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.IntextIpProtocolType) BigInteger(java.math.BigInteger) IpPortExternal(org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.ip.port.map.IpPortExternal)

Aggregations

IpPortExternal (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.ip.port.map.IpPortExternal)5 BigInteger (java.math.BigInteger)4 IpPortMap (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.intext.ip.protocol.type.IpPortMap)4 ProtocolTypes (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ProtocolTypes)3 IpPortMapping (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.IpPortMapping)3 IntextIpProtocolType (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.intext.ip.port.map.ip.port.mapping.IntextIpProtocolType)3 ArrayList (java.util.ArrayList)2 ExecutionException (java.util.concurrent.ExecutionException)2 Uuid (org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid)2 IntextIpPortMap (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.IntextIpPortMap)2 SnatintIpPortMap (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.SnatintIpPortMap)2 IpPort (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.IpPort)2 IntIpProtoType (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.snatint.ip.port.map.intip.port.map.ip.port.IntIpProtoType)2 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)1 UncheckedExecutionException (com.google.common.util.concurrent.UncheckedExecutionException)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Map (java.util.Map)1 SubnetUtils (org.apache.commons.net.util.SubnetUtils)1