Remove NatUtil::read()
[netvirt.git] / vpnservice / natservice / natservice-impl / src / main / java / org / opendaylight / netvirt / natservice / internal / FloatingIPListener.java
1 /*
2  * Copyright © 2016, 2017 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.netvirt.natservice.internal;
9
10 import com.google.common.base.Optional;
11 import java.math.BigInteger;
12 import java.net.InetAddress;
13 import java.net.UnknownHostException;
14 import java.util.ArrayList;
15 import java.util.List;
16 import javax.annotation.PostConstruct;
17 import javax.inject.Inject;
18 import javax.inject.Singleton;
19 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.genius.datastoreutils.AsyncDataTreeChangeListenerBase;
22 import org.opendaylight.genius.datastoreutils.SingleTransactionDataBroker;
23 import org.opendaylight.genius.mdsalutil.ActionInfo;
24 import org.opendaylight.genius.mdsalutil.FlowEntity;
25 import org.opendaylight.genius.mdsalutil.InstructionInfo;
26 import org.opendaylight.genius.mdsalutil.MDSALUtil;
27 import org.opendaylight.genius.mdsalutil.MatchInfo;
28 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
29 import org.opendaylight.genius.mdsalutil.NwConstants;
30 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
31 import org.opendaylight.genius.mdsalutil.actions.ActionSetDestinationIp;
32 import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldEthernetSource;
33 import org.opendaylight.genius.mdsalutil.actions.ActionSetSourceIp;
34 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
35 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
36 import org.opendaylight.genius.mdsalutil.instructions.InstructionWriteMetadata;
37 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
38 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
39 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
40 import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Destination;
41 import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Source;
42 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ExternalNetworks;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.FloatingIpInfo;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.ProviderTypes;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.external.networks.Networks;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.external.networks.NetworksKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.RouterPorts;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.Ports;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.PortsBuilder;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.PortsKey;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.ports.InternalToExternalPortMap;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.ports.InternalToExternalPortMapBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.natservice.rev160111.floating.ip.info.router.ports.ports.InternalToExternalPortMapKey;
58 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 @Singleton
63 public class FloatingIPListener extends AsyncDataTreeChangeListenerBase<InternalToExternalPortMap, FloatingIPListener>
64         implements AutoCloseable {
65     private static final Logger LOG = LoggerFactory.getLogger(FloatingIPListener.class);
66     private final DataBroker dataBroker;
67     private final IMdsalApiManager mdsalManager;
68     private final OdlInterfaceRpcService interfaceManager;
69     private final FloatingIPHandler floatingIPHandler;
70
71     @Inject
72     public FloatingIPListener(final DataBroker dataBroker, final IMdsalApiManager mdsalManager,
73                               final OdlInterfaceRpcService interfaceManager,
74                               final FloatingIPHandler floatingIPHandler) {
75         super(InternalToExternalPortMap.class, FloatingIPListener.class);
76         this.dataBroker = dataBroker;
77         this.mdsalManager = mdsalManager;
78         this.interfaceManager = interfaceManager;
79         this.floatingIPHandler = floatingIPHandler;
80     }
81
82     @Override
83     @PostConstruct
84     public void init() {
85         LOG.info("{} init", getClass().getSimpleName());
86         registerListener(LogicalDatastoreType.CONFIGURATION, dataBroker);
87     }
88
89     @Override
90     protected InstanceIdentifier<InternalToExternalPortMap> getWildCardPath() {
91         return InstanceIdentifier.create(FloatingIpInfo.class).child(RouterPorts.class).child(Ports.class)
92                 .child(InternalToExternalPortMap.class);
93     }
94
95     @Override
96     protected FloatingIPListener getDataTreeChangeListener() {
97         return FloatingIPListener.this;
98     }
99
100     @Override
101     protected void add(final InstanceIdentifier<InternalToExternalPortMap> identifier,
102                        final InternalToExternalPortMap mapping) {
103         LOG.trace("FloatingIPListener add ip mapping method - key: " + identifier + ", value=" + mapping);
104         processFloatingIPAdd(identifier, mapping);
105     }
106
107     @Override
108     protected void remove(InstanceIdentifier<InternalToExternalPortMap> identifier, InternalToExternalPortMap mapping) {
109         LOG.trace("FloatingIPListener remove ip mapping method - key: " + identifier + ", value=" + mapping);
110         processFloatingIPDel(identifier, mapping);
111     }
112
113     @Override
114     protected void update(InstanceIdentifier<InternalToExternalPortMap> identifier, InternalToExternalPortMap
115             original, InternalToExternalPortMap update) {
116         LOG.trace("FloatingIPListener update ip mapping method - key: {}, original: {}, update: {}",
117             identifier, original, update);
118     }
119
120     private FlowEntity buildPreDNATFlowEntity(BigInteger dpId, InternalToExternalPortMap mapping, long routerId, long
121             associatedVpn) {
122         String externalIp = mapping.getExternalIp();
123         Uuid floatingIpId = mapping.getExternalId();
124         //Get the FIP MAC address for DNAT
125         String floatingIpPortMacAddress = NatUtil.getFloatingIpPortMacFromFloatingIpId(dataBroker, floatingIpId);
126         if (floatingIpPortMacAddress == null) {
127             LOG.error("NAT Service : Unable to retrieve floatingIpPortMacAddress from floating IP UUID {} "
128                     + "for floating IP {}", floatingIpId, externalIp);
129             return null;
130         }
131         LOG.info("NAT Service : Bulding DNAT Flow entity for ip {} ", externalIp);
132         long segmentId = (associatedVpn == NatConstants.INVALID_ID) ? routerId : associatedVpn;
133         LOG.debug("NAT Service : Segment id {} in build preDNAT Flow", segmentId);
134
135         List<MatchInfo> matches = new ArrayList<>();
136         matches.add(MatchEthernetType.IPV4);
137
138         matches.add(new MatchIpv4Destination(externalIp, "32"));
139         //Match Destination Floating IP MAC Address on table = 25 (PDNAT_TABLE)
140         matches.add(new MatchEthernetDestination(new MacAddress(floatingIpPortMacAddress)));
141
142 //        matches.add(new MatchMetadata(
143 //                BigInteger.valueOf(vpnId), MetaDataUtil.METADATA_MASK_VRFID));
144         List<ActionInfo> actionsInfos = new ArrayList<>();
145         String internalIp = mapping.getInternalIp();
146         actionsInfos.add(new ActionSetDestinationIp(internalIp, "32"));
147
148         List<InstructionInfo> instructions = new ArrayList<>();
149         instructions.add(new InstructionWriteMetadata(MetaDataUtil.getVpnIdMetadata(segmentId),
150                 MetaDataUtil.METADATA_MASK_VRFID));
151         instructions.add(new InstructionApplyActions(actionsInfos));
152         instructions.add(new InstructionGotoTable(NwConstants.DNAT_TABLE));
153
154         String flowRef = NatUtil.getFlowRef(dpId, NwConstants.PDNAT_TABLE, routerId, externalIp);
155
156         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.PDNAT_TABLE, flowRef,
157                 NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0,
158                 NwConstants.COOKIE_DNAT_TABLE, matches, instructions);
159
160         return flowEntity;
161     }
162
163     private FlowEntity buildDNATFlowEntity(BigInteger dpId, InternalToExternalPortMap mapping, long routerId, long
164             associatedVpn) {
165         String externalIp = mapping.getExternalIp();
166         LOG.info("NAT Service : Bulding DNAT Flow entity for ip {} ", externalIp);
167
168         long segmentId = (associatedVpn == NatConstants.INVALID_ID) ? routerId : associatedVpn;
169         LOG.debug("NAT Service : Segment id {} in build DNAT", segmentId);
170
171         List<MatchInfo> matches = new ArrayList<>();
172         matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(segmentId), MetaDataUtil.METADATA_MASK_VRFID));
173
174         matches.add(MatchEthernetType.IPV4);
175         String internalIp = mapping.getInternalIp();
176         matches.add(new MatchIpv4Destination(internalIp, "32"));
177
178         List<ActionInfo> actionsInfos = new ArrayList<>();
179 //        actionsInfos.add(new ActionSetDestinationIp(internalIp, "32"));
180
181         List<InstructionInfo> instructions = new ArrayList<>();
182 //        instructions.add(new InstructionWriteMetadata(BigInteger.valueOf
183 //                (routerId), MetaDataUtil.METADATA_MASK_VRFID));
184         actionsInfos.add(new ActionNxResubmit(NwConstants.L3_FIB_TABLE));
185         instructions.add(new InstructionApplyActions(actionsInfos));
186         //instructions.add(new InstructionGotoTable(NatConstants.L3_FIB_TABLE));
187
188         String flowRef = NatUtil.getFlowRef(dpId, NwConstants.DNAT_TABLE, routerId, internalIp);
189
190         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.DNAT_TABLE, flowRef,
191                 NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0,
192                 NwConstants.COOKIE_DNAT_TABLE, matches, instructions);
193
194         return flowEntity;
195
196     }
197
198     private FlowEntity buildPreSNATFlowEntity(BigInteger dpId, String internalIp, String externalIp, long vpnId, long
199             routerId, long associatedVpn) {
200
201         LOG.info("NAT Service : Building PSNAT Flow entity for ip {} ", internalIp);
202
203         long segmentId = (associatedVpn == NatConstants.INVALID_ID) ? routerId : associatedVpn;
204
205         LOG.debug("NAT Service : Segment id {} in build preSNAT flow", segmentId);
206
207         List<MatchInfo> matches = new ArrayList<>();
208         matches.add(MatchEthernetType.IPV4);
209
210         matches.add(new MatchIpv4Source(internalIp, "32"));
211
212         matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(segmentId), MetaDataUtil.METADATA_MASK_VRFID));
213
214         List<ActionInfo> actionsInfos = new ArrayList<>();
215         actionsInfos.add(new ActionSetSourceIp(externalIp, "32"));
216
217         List<InstructionInfo> instructions = new ArrayList<>();
218         instructions.add(
219                 new InstructionWriteMetadata(MetaDataUtil.getVpnIdMetadata(vpnId), MetaDataUtil.METADATA_MASK_VRFID));
220         instructions.add(new InstructionApplyActions(actionsInfos));
221         instructions.add(new InstructionGotoTable(NwConstants.SNAT_TABLE));
222
223         String flowRef = NatUtil.getFlowRef(dpId, NwConstants.PSNAT_TABLE, routerId, internalIp);
224
225         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.PSNAT_TABLE, flowRef,
226                 NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0,
227                 NwConstants.COOKIE_DNAT_TABLE, matches, instructions);
228
229         return flowEntity;
230     }
231
232     private FlowEntity buildSNATFlowEntity(BigInteger dpId, InternalToExternalPortMap mapping, long vpnId, Uuid
233             externalNetworkId) {
234         String internalIp = mapping.getInternalIp();
235         LOG.info("Building SNAT Flow entity for ip {} ", internalIp);
236
237         ProviderTypes provType = NatUtil.getProviderTypefromNetworkId(dataBroker, externalNetworkId);
238         if (provType == null) {
239             LOG.error("NAT Service : Unable to get Network Provider Type for network {}", externalNetworkId);
240             return null;
241         }
242
243         List<MatchInfo> matches = new ArrayList<>();
244         matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(vpnId), MetaDataUtil.METADATA_MASK_VRFID));
245         matches.add(MatchEthernetType.IPV4);
246         String externalIp = mapping.getExternalIp();
247         matches.add(new MatchIpv4Source(externalIp, "32"));
248
249         List<ActionInfo> actionsInfo = new ArrayList<>();
250         Uuid floatingIpId = mapping.getExternalId();
251         String macAddress = NatUtil.getFloatingIpPortMacFromFloatingIpId(dataBroker, floatingIpId);
252         if (macAddress != null) {
253             actionsInfo.add(new ActionSetFieldEthernetSource(new MacAddress(macAddress)));
254         } else {
255             LOG.warn("No MAC address found for floating IP {}", externalIp);
256         }
257
258         LOG.trace("NAT Service : External Network Provider Type is {}, resubmit to FIB", provType.toString());
259         actionsInfo.add(new ActionNxResubmit(NwConstants.L3_FIB_TABLE));
260         List<InstructionInfo> instructions = new ArrayList<>();
261         instructions.add(new InstructionApplyActions(actionsInfo));
262         String flowRef = NatUtil.getFlowRef(dpId, NwConstants.SNAT_TABLE, vpnId, externalIp);
263
264         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.SNAT_TABLE, flowRef,
265                 NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0,
266                 NwConstants.COOKIE_DNAT_TABLE, matches, instructions);
267
268         return flowEntity;
269
270     }
271
272     private void createDNATTblEntry(BigInteger dpnId, InternalToExternalPortMap mapping, long routerId, long vpnId,
273                                     long associatedVpnId) {
274         FlowEntity preFlowEntity = buildPreDNATFlowEntity(dpnId, mapping, routerId, associatedVpnId);
275         if (preFlowEntity == null) {
276             LOG.error("NAT Service : Flow entity received as NULL. Cannot proceed with installation of Pre-DNAT flow "
277                     + "table {} --> table {} on DpnId {}", NwConstants.PDNAT_TABLE, NwConstants.DNAT_TABLE, dpnId);
278         } else {
279             mdsalManager.installFlow(preFlowEntity);
280             FlowEntity flowEntity = buildDNATFlowEntity(dpnId, mapping, routerId, associatedVpnId);
281             mdsalManager.installFlow(flowEntity);
282         }
283     }
284
285     private void removeDNATTblEntry(BigInteger dpnId, String internalIp, String externalIp, long routerId) {
286         FlowEntity preFlowEntity = buildPreDNATDeleteFlowEntity(dpnId, externalIp, routerId);
287         mdsalManager.removeFlow(preFlowEntity);
288
289         FlowEntity flowEntity = buildDNATDeleteFlowEntity(dpnId, internalIp, routerId);
290         mdsalManager.removeFlow(flowEntity);
291     }
292
293     private void createSNATTblEntry(BigInteger dpnId, InternalToExternalPortMap mapping, long vpnId, long routerId,
294                                     long associatedVpnId, Uuid externalNetworkId) {
295         FlowEntity preFlowEntity = buildPreSNATFlowEntity(dpnId, mapping.getInternalIp(), mapping.getExternalIp(),
296             vpnId, routerId, associatedVpnId);
297         mdsalManager.installFlow(preFlowEntity);
298
299         FlowEntity flowEntity = buildSNATFlowEntity(dpnId, mapping, vpnId, externalNetworkId);
300         mdsalManager.installFlow(flowEntity);
301     }
302
303     private void removeSNATTblEntry(BigInteger dpnId, String internalIp, String externalIp, long routerId, long vpnId) {
304         FlowEntity preFlowEntity = buildPreSNATDeleteFlowEntity(dpnId, internalIp, routerId);
305         mdsalManager.removeFlow(preFlowEntity);
306
307         FlowEntity flowEntity = buildSNATDeleteFlowEntity(dpnId, externalIp, vpnId);
308         mdsalManager.removeFlow(flowEntity);
309     }
310
311     private Uuid getExtNetworkId(final InstanceIdentifier<RouterPorts> portIid,
312                                  LogicalDatastoreType dataStoreType) {
313         Optional<RouterPorts> rtrPort =
314                 SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker,
315                         dataStoreType, portIid);
316         if (!rtrPort.isPresent()) {
317             LOG.error("NAT Service : Unable to read router port entry for {}", portIid);
318             return null;
319         }
320
321         Uuid extNwId = rtrPort.get().getExternalNetworkId();
322         return extNwId;
323     }
324
325     private long getVpnId(Uuid extNwId, Uuid floatingIpExternalId) {
326         Uuid subnetId = NatUtil.getFloatingIpPortSubnetIdFromFloatingIpId(dataBroker, floatingIpExternalId);
327         if (subnetId != null) {
328             long vpnId = NatUtil.getVpnId(dataBroker, subnetId.getValue());
329             if (vpnId != NatConstants.INVALID_ID) {
330                 LOG.debug("Got vpnId {} for floatingIpExternalId {}", vpnId, floatingIpExternalId);
331                 return vpnId;
332             }
333         }
334
335         InstanceIdentifier<Networks> nwId = InstanceIdentifier.builder(ExternalNetworks.class).child(Networks.class,
336                 new NetworksKey(extNwId)).build();
337         Optional<Networks> nw =
338                 SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker,
339                         LogicalDatastoreType.CONFIGURATION, nwId);
340         if (!nw.isPresent()) {
341             LOG.error("NAT Service : Unable to read external network for {}", extNwId);
342             return NatConstants.INVALID_ID;
343         }
344
345         Uuid vpnUuid = nw.get().getVpnid();
346         if (vpnUuid == null) {
347             return NatConstants.INVALID_ID;
348         }
349
350         //Get the id using the VPN UUID (also vpn instance name)
351         return NatUtil.readVpnId(dataBroker, vpnUuid.getValue());
352     }
353
354     private void processFloatingIPAdd(final InstanceIdentifier<InternalToExternalPortMap> identifier,
355                                       final InternalToExternalPortMap mapping) {
356         LOG.trace("Add event - key: {}, value: {}", identifier, mapping);
357
358         final String routerId = identifier.firstKeyOf(RouterPorts.class).getRouterId();
359         final PortsKey pKey = identifier.firstKeyOf(Ports.class);
360         String interfaceName = pKey.getPortName();
361
362         InstanceIdentifier<RouterPorts> portIid = identifier.firstIdentifierOf(RouterPorts.class);
363         createNATFlowEntries(interfaceName, mapping, portIid, routerId);
364     }
365
366     private void processFloatingIPDel(final InstanceIdentifier<InternalToExternalPortMap> identifier,
367                                       final InternalToExternalPortMap mapping) {
368         LOG.trace("Del event - key: {}, value: {}", identifier, mapping);
369
370         final String routerId = identifier.firstKeyOf(RouterPorts.class).getRouterId();
371         final PortsKey pKey = identifier.firstKeyOf(Ports.class);
372         String interfaceName = pKey.getPortName();
373
374         InstanceIdentifier<RouterPorts> portIid = identifier.firstIdentifierOf(RouterPorts.class);
375         removeNATFlowEntries(interfaceName, mapping, portIid, routerId, null);
376     }
377
378     private InetAddress getInetAddress(String ipAddr) {
379         InetAddress ipAddress = null;
380         try {
381             ipAddress = InetAddress.getByName(ipAddr);
382         } catch (UnknownHostException e) {
383             LOG.error("NAT Service : UnknowHostException for ip {}", ipAddr);
384         }
385         return ipAddress;
386     }
387
388     private boolean validateIpMapping(InternalToExternalPortMap mapping) {
389         return getInetAddress(mapping.getInternalIp()) != null && getInetAddress(mapping.getExternalIp()) != null;
390     }
391
392     void createNATFlowEntries(String interfaceName, final InternalToExternalPortMap mapping,
393                               final InstanceIdentifier<RouterPorts> portIid, final String routerName) {
394         if (!validateIpMapping(mapping)) {
395             LOG.warn("NAT Service : Not a valid ip addresses in the mapping {}", mapping);
396             return;
397         }
398
399         //Get the DPN on which this interface resides
400         BigInteger dpnId = NatUtil.getDpnForInterface(interfaceManager, interfaceName);
401
402         if (dpnId.equals(BigInteger.ZERO)) {
403             LOG.error("NAT Service : No DPN for interface {}. NAT flow entries for ip mapping {} will "
404                 + "not be installed", interfaceName, mapping);
405             return;
406         }
407
408         long routerId = NatUtil.getVpnId(dataBroker, routerName);
409         if (routerId == NatConstants.INVALID_ID) {
410             LOG.warn("NAT Service : Could not retrieve router id for {} to create NAT Flow entries", routerName);
411             return;
412         }
413         //Check if the router to vpn association is present
414         //long associatedVpnId = NatUtil.getAssociatedVpn(dataBroker, routerName);
415         Uuid associatedVpn = NatUtil.getVpnForRouter(dataBroker, routerName);
416         long associatedVpnId = NatConstants.INVALID_ID;
417         if (associatedVpn == null) {
418             LOG.debug("NAT Service : Router {} is not assicated with any BGP VPN instance", routerName);
419         } else {
420             LOG.debug("NAT Service : Router {} is associated with VPN Instance with Id {}", routerName, associatedVpn);
421             associatedVpnId = NatUtil.getVpnId(dataBroker, associatedVpn.getValue());
422             LOG.debug("NAT Service : vpninstance Id is {} for VPN {}", associatedVpnId, associatedVpn);
423             //routerId = associatedVpnId;
424         }
425
426         Uuid extNwId = getExtNetworkId(portIid, LogicalDatastoreType.CONFIGURATION);
427         if (extNwId == null) {
428             LOG.error("NAT Service : External network associated with interface {} could not be retrieved",
429                 interfaceName);
430             LOG.error("NAT Service : NAT flow entries will not be installed {}", mapping);
431             return;
432         }
433         long vpnId = getVpnId(extNwId, mapping.getExternalId());
434         if (vpnId < 0) {
435             LOG.error("NAT Service : No VPN associated with Ext nw {}. Unable to create SNAT table entry "
436                     + "for fixed ip {}", extNwId, mapping.getInternalIp());
437             return;
438         }
439
440         //Create the DNAT and SNAT table entries
441         createDNATTblEntry(dpnId, mapping, routerId, vpnId, associatedVpnId);
442
443
444         createSNATTblEntry(dpnId, mapping, vpnId, routerId, associatedVpnId, extNwId);
445
446         floatingIPHandler.onAddFloatingIp(dpnId, routerName, extNwId, interfaceName, mapping);
447     }
448
449     void createNATFlowEntries(BigInteger dpnId,  String interfaceName, String routerName, Uuid externalNetworkId,
450                               InternalToExternalPortMap mapping) {
451         String internalIp = mapping.getInternalIp();
452         long routerId = NatUtil.getVpnId(dataBroker, routerName);
453         if (routerId == NatConstants.INVALID_ID) {
454             LOG.warn("NAT Service : Could not retrieve router id for {} to create NAT Flow entries", routerName);
455             return;
456         }
457         //Check if the router to vpn association is present
458         long associatedVpnId = NatUtil.getAssociatedVpn(dataBroker, routerName);
459         if (associatedVpnId == NatConstants.INVALID_ID) {
460             LOG.debug("NAT Service : Router {} is not assicated with any BGP VPN instance", routerName);
461         } else {
462             LOG.debug("NAT Service : Router {} is associated with VPN Instance with Id {}",
463                 routerName, associatedVpnId);
464             //routerId = associatedVpnId;
465         }
466
467         long vpnId = getVpnId(externalNetworkId, mapping.getExternalId());
468         if (vpnId < 0) {
469             LOG.error("NAT Service : Unable to create SNAT table entry for fixed ip {}", internalIp);
470             return;
471         }
472         //Create the DNAT and SNAT table entries
473         createDNATTblEntry(dpnId, mapping, routerId, vpnId, associatedVpnId);
474
475         createSNATTblEntry(dpnId, mapping, vpnId, routerId, associatedVpnId, externalNetworkId);
476
477         floatingIPHandler.onAddFloatingIp(dpnId, routerName, externalNetworkId, interfaceName, mapping);
478     }
479
480     void createNATOnlyFlowEntries(BigInteger dpnId, String routerName, String associatedVPN,
481                                   Uuid externalNetworkId, InternalToExternalPortMap mapping) {
482         String internalIp = mapping.getInternalIp();
483         //String segmentId = associatedVPN == null ? routerName : associatedVPN;
484         LOG.debug("NAT Service : Retrieving vpn id for VPN {} to proceed with create NAT Flows", routerName);
485         long routerId = NatUtil.getVpnId(dataBroker, routerName);
486         if (routerId == NatConstants.INVALID_ID) {
487             LOG.warn("Could not retrieve vpn id for {} to create NAT Flow entries", routerName);
488             return;
489         }
490         long associatedVpnId = NatUtil.getVpnId(dataBroker, associatedVPN);
491         LOG.debug("NAT Service : Associated VPN Id {} for router {}", associatedVpnId, routerName);
492         long vpnId = getVpnId(externalNetworkId, mapping.getExternalId());
493         if (vpnId < 0) {
494             LOG.error("NAT Service : Unable to create SNAT table entry for fixed ip {}", internalIp);
495             return;
496         }
497         //Create the DNAT and SNAT table entries
498         FlowEntity preFlowEntity = buildPreDNATFlowEntity(dpnId, mapping, routerId, associatedVpnId);
499         mdsalManager.installFlow(preFlowEntity);
500
501         FlowEntity flowEntity = buildDNATFlowEntity(dpnId, mapping, routerId, associatedVpnId);
502         mdsalManager.installFlow(flowEntity);
503
504         String externalIp = mapping.getExternalIp();
505         preFlowEntity = buildPreSNATFlowEntity(dpnId, internalIp, externalIp, vpnId , routerId, associatedVpnId);
506         mdsalManager.installFlow(preFlowEntity);
507
508         flowEntity = buildSNATFlowEntity(dpnId, mapping, vpnId, externalNetworkId);
509         mdsalManager.installFlow(flowEntity);
510
511     }
512
513     void removeNATFlowEntries(String interfaceName, final InternalToExternalPortMap mapping,
514                               InstanceIdentifier<RouterPorts> portIid, final String routerName, BigInteger dpnId) {
515         String internalIp = mapping.getInternalIp();
516         String externalIp = mapping.getExternalIp();
517         //Get the DPN on which this interface resides
518         if (dpnId == null) {
519             dpnId = NatUtil.getDpnForInterface(interfaceManager, interfaceName);
520             if (dpnId.equals(BigInteger.ZERO)) {
521                 LOG.info("NAT Service: Abort processing Floating ip configuration. No DPN for port: {}", interfaceName);
522                 return;
523             }
524         }
525
526         long routerId = NatUtil.getVpnId(dataBroker, routerName);
527         if (routerId == NatConstants.INVALID_ID) {
528             LOG.warn("NAT Service : Could not retrieve router id for {} to remove NAT Flow entries", routerName);
529             return;
530         }
531
532         //Delete the DNAT and SNAT table entries
533         removeDNATTblEntry(dpnId, internalIp, externalIp, routerId);
534
535         Uuid extNwId = getExtNetworkId(portIid, LogicalDatastoreType.OPERATIONAL);
536         if (extNwId == null) {
537             LOG.error("NAT Service : External network associated with interface {} could not be retrieved",
538                 interfaceName);
539             return;
540         }
541         long vpnId = getVpnId(extNwId, mapping.getExternalId());
542         if (vpnId < 0) {
543             LOG.error("NAT Service : No VPN associated with ext nw {}. Unable to delete SNAT table "
544                 + "entry for fixed ip {}", extNwId, internalIp);
545             return;
546         }
547         removeSNATTblEntry(dpnId, internalIp, externalIp, routerId, vpnId);
548         ProviderTypes provType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName);
549         if (provType == null) {
550             return;
551         }
552         if (provType == ProviderTypes.VXLAN) {
553             floatingIPHandler.onRemoveFloatingIp(dpnId, routerName, extNwId, mapping, NatConstants.DEFAULT_L3VNI_VALUE);
554             removeOperationalDS(routerName, interfaceName, internalIp, externalIp);
555             return;
556         }
557         long label = getOperationalIpMapping(routerName, interfaceName, internalIp);
558         if (label < 0) {
559             LOG.error("NAT Service : Could not retrieve label for prefix {} in router {}", internalIp, routerId);
560             return;
561         }
562         floatingIPHandler.onRemoveFloatingIp(dpnId, routerName, extNwId, mapping, (int) label);
563         removeOperationalDS(routerName, interfaceName, internalIp, externalIp);
564     }
565
566     void removeNATFlowEntries(BigInteger dpnId, String interfaceName, String vpnName, String routerName,
567                               InternalToExternalPortMap mapping) {
568         String internalIp = mapping.getInternalIp();
569         String externalIp = mapping.getExternalIp();
570         long routerId = NatUtil.getVpnId(dataBroker, routerName);
571         if (routerId == NatConstants.INVALID_ID) {
572             LOG.warn("NAT Service : Could not retrieve router id for {} to remove NAT Flow entries", routerName);
573             return;
574         }
575
576         long vpnId = NatUtil.getVpnId(dataBroker, vpnName);
577         if (vpnId == NatConstants.INVALID_ID) {
578             LOG.warn("NAT Service : VPN Id not found for {} to remove NAT flow entries {}", vpnName, internalIp);
579         }
580
581         //Delete the DNAT and SNAT table entries
582         removeDNATTblEntry(dpnId, internalIp, externalIp, routerId);
583
584         removeSNATTblEntry(dpnId, internalIp, externalIp, routerId, vpnId);
585         ProviderTypes provType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerName);
586         if (provType == null) {
587             return;
588         }
589         if (provType == ProviderTypes.VXLAN) {
590             floatingIPHandler.cleanupFibEntries(dpnId, vpnName, externalIp, NatConstants.DEFAULT_L3VNI_VALUE);
591             removeOperationalDS(routerName, interfaceName, internalIp, externalIp);
592             return;
593         }
594         long label = getOperationalIpMapping(routerName, interfaceName, internalIp);
595         if (label < 0) {
596             LOG.error("NAT Service : Could not retrieve label for prefix {} in router {}", internalIp, routerId);
597             return;
598         }
599         floatingIPHandler.cleanupFibEntries(dpnId, vpnName, externalIp, label);
600         removeOperationalDS(routerName, interfaceName, internalIp, externalIp);
601     }
602
603     protected long getOperationalIpMapping(String routerId, String interfaceName, String internalIp) {
604         InstanceIdentifier<InternalToExternalPortMap> intExtPortMapIdentifier =
605             NatUtil.getIntExtPortMapIdentifier(routerId, interfaceName, internalIp);
606         return SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker,
607                 LogicalDatastoreType.OPERATIONAL, intExtPortMapIdentifier).transform(
608                 InternalToExternalPortMap::getLabel).or(NatConstants.INVALID_ID);
609     }
610
611     static void updateOperationalDS(DataBroker dataBroker, String routerId, String interfaceName, long label,
612                                     String internalIp, String externalIp) {
613
614         LOG.info("NAT Service : Updating operational DS for floating ip config : {} with label {}", internalIp, label);
615         InstanceIdentifier<Ports> portsId = NatUtil.getPortsIdentifier(routerId, interfaceName);
616         Optional<Ports> optPorts =
617                 SingleTransactionDataBroker.syncReadOptionalAndTreatReadFailedExceptionAsAbsentOptional(dataBroker,
618                         LogicalDatastoreType.OPERATIONAL, portsId);
619         InternalToExternalPortMap intExtPortMap = new InternalToExternalPortMapBuilder().setKey(new
620                 InternalToExternalPortMapKey(internalIp)).setInternalIp(internalIp).setExternalIp(externalIp)
621                 .setLabel(label).build();
622         if (optPorts.isPresent()) {
623             LOG.debug("Ports {} entry already present. Updating intExtPortMap for internal ip {}", interfaceName,
624                     internalIp);
625             MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.OPERATIONAL, portsId.child(InternalToExternalPortMap
626                     .class, new InternalToExternalPortMapKey(internalIp)), intExtPortMap);
627         } else {
628             LOG.debug("Adding Ports entry {} along with intExtPortMap {}", interfaceName, internalIp);
629             List<InternalToExternalPortMap> intExtPortMapList = new ArrayList<>();
630             intExtPortMapList.add(intExtPortMap);
631             Ports ports = new PortsBuilder().setKey(new PortsKey(interfaceName)).setPortName(interfaceName)
632                     .setInternalToExternalPortMap(intExtPortMapList).build();
633             MDSALUtil.syncWrite(dataBroker, LogicalDatastoreType.OPERATIONAL, portsId, ports);
634         }
635     }
636
637     void removeOperationalDS(String routerId, String interfaceName, String internalIp, String externalIp) {
638         LOG.info("Remove operational DS for floating ip config: {}", internalIp);
639         InstanceIdentifier<InternalToExternalPortMap> intExtPortMapId = NatUtil.getIntExtPortMapIdentifier(routerId,
640                 interfaceName, internalIp);
641         MDSALUtil.syncDelete(dataBroker, LogicalDatastoreType.OPERATIONAL, intExtPortMapId);
642     }
643
644     private FlowEntity buildPreDNATDeleteFlowEntity(BigInteger dpId, String externalIp, long routerId) {
645
646         LOG.info("NAT Service : Bulding Delete DNAT Flow entity for ip {} ", externalIp);
647
648         String flowRef = NatUtil.getFlowRef(dpId, NwConstants.PDNAT_TABLE, routerId, externalIp);
649
650         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.PDNAT_TABLE, flowRef,
651                 NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0,
652                 NwConstants.COOKIE_DNAT_TABLE, null, null);
653
654         return flowEntity;
655     }
656
657
658
659     private FlowEntity buildDNATDeleteFlowEntity(BigInteger dpId, String internalIp, long routerId) {
660
661         LOG.info("NAT Service : Bulding Delete DNAT Flow entity for ip {} ", internalIp);
662
663         String flowRef = NatUtil.getFlowRef(dpId, NwConstants.DNAT_TABLE, routerId, internalIp);
664
665         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.DNAT_TABLE, flowRef,
666                 NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0,
667                 NwConstants.COOKIE_DNAT_TABLE, null, null);
668
669         return flowEntity;
670
671     }
672
673     private FlowEntity buildPreSNATDeleteFlowEntity(BigInteger dpId, String internalIp, long routerId) {
674
675         LOG.info("NAT Service : Building Delete PSNAT Flow entity for ip {} ", internalIp);
676
677         String flowRef = NatUtil.getFlowRef(dpId, NwConstants.PSNAT_TABLE, routerId, internalIp);
678
679         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.PSNAT_TABLE, flowRef,
680                 NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0,
681                 NwConstants.COOKIE_DNAT_TABLE, null, null);
682         return flowEntity;
683     }
684
685     private FlowEntity buildSNATDeleteFlowEntity(BigInteger dpId, String externalIp, long routerId) {
686
687         LOG.info("NAT Service : Building Delete SNAT Flow entity for ip {} ", externalIp);
688
689         String flowRef = NatUtil.getFlowRef(dpId, NwConstants.SNAT_TABLE, routerId, externalIp);
690
691         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.SNAT_TABLE, flowRef,
692                 NatConstants.DEFAULT_DNAT_FLOW_PRIORITY, flowRef, 0, 0,
693                 NwConstants.COOKIE_DNAT_TABLE, null, null);
694
695         return flowEntity;
696     }
697 }
698