NETVIRT-1068: Upstreaming fixes 2
[netvirt.git] / fibmanager / impl / src / main / java / org / opendaylight / netvirt / fibmanager / BaseVrfEntryHandler.java
1 /*
2  * Copyright © 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.fibmanager;
9
10 import static java.util.stream.Collectors.toList;
11 import static org.opendaylight.genius.mdsalutil.NWUtil.isIpv4Address;
12
13 import com.google.common.base.Optional;
14 import java.math.BigInteger;
15 import java.net.Inet4Address;
16 import java.net.InetAddress;
17 import java.net.UnknownHostException;
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.List;
21 import javax.annotation.Nonnull;
22 import javax.inject.Inject;
23 import javax.inject.Singleton;
24 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
25 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
26 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
27 import org.opendaylight.genius.mdsalutil.ActionInfo;
28 import org.opendaylight.genius.mdsalutil.FlowEntity;
29 import org.opendaylight.genius.mdsalutil.InstructionInfo;
30 import org.opendaylight.genius.mdsalutil.MDSALUtil;
31 import org.opendaylight.genius.mdsalutil.MatchInfo;
32 import org.opendaylight.genius.mdsalutil.MetaDataUtil;
33 import org.opendaylight.genius.mdsalutil.NwConstants;
34 import org.opendaylight.genius.mdsalutil.actions.ActionMoveSourceDestinationEth;
35 import org.opendaylight.genius.mdsalutil.actions.ActionMoveSourceDestinationIp;
36 import org.opendaylight.genius.mdsalutil.actions.ActionNxLoadInPort;
37 import org.opendaylight.genius.mdsalutil.actions.ActionNxResubmit;
38 import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldEthernetDestination;
39 import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldEthernetSource;
40 import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldTunnelId;
41 import org.opendaylight.genius.mdsalutil.actions.ActionSetIcmpType;
42 import org.opendaylight.genius.mdsalutil.actions.ActionSetSourceIp;
43 import org.opendaylight.genius.mdsalutil.instructions.InstructionApplyActions;
44 import org.opendaylight.genius.mdsalutil.instructions.InstructionGotoTable;
45 import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager;
46 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetDestination;
47 import org.opendaylight.genius.mdsalutil.matches.MatchEthernetType;
48 import org.opendaylight.genius.mdsalutil.matches.MatchIcmpv4;
49 import org.opendaylight.genius.mdsalutil.matches.MatchIpProtocol;
50 import org.opendaylight.genius.mdsalutil.matches.MatchIpv4Destination;
51 import org.opendaylight.genius.mdsalutil.matches.MatchIpv6Destination;
52 import org.opendaylight.genius.mdsalutil.matches.MatchMetadata;
53 import org.opendaylight.genius.utils.batching.SubTransaction;
54 import org.opendaylight.genius.utils.batching.SubTransactionImpl;
55 import org.opendaylight.netvirt.fibmanager.NexthopManager.AdjacencyResult;
56 import org.opendaylight.netvirt.fibmanager.api.FibHelper;
57 import org.opendaylight.netvirt.fibmanager.api.RouteOrigin;
58 import org.opendaylight.netvirt.vpnmanager.api.VpnExtraRouteHelper;
59 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeBase;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rev160406.TunnelTypeVxlan;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.fibentries.VrfTablesKey;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentries.VrfEntry;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentrybase.RoutePaths;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3nexthop.rev150409.l3nexthop.vpnnexthops.VpnNexthop;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.VpnToExtraroutes;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.vpn.ids.Prefixes;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroutes.Vpn;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroutes.VpnKey;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroutes.vpn.ExtraRoutes;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroutes.vpn.ExtraRoutesKey;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroutes.vpn.extra.routes.Routes;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroutes.vpn.extra.routes.RoutesKey;
83 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
86
87
88 @Singleton
89 public class BaseVrfEntryHandler implements AutoCloseable {
90
91     private static final Logger LOG = LoggerFactory.getLogger(BaseVrfEntryHandler.class);
92     private static final BigInteger COOKIE_VM_FIB_TABLE =  new BigInteger("8000003", 16);
93     private static final int DEFAULT_FIB_FLOW_PRIORITY = 10;
94
95     private final DataBroker dataBroker;
96     private final NexthopManager nextHopManager;
97     private final IMdsalApiManager mdsalManager;
98     private final FibUtil fibUtil;
99
100     @Inject
101     public BaseVrfEntryHandler(final DataBroker dataBroker,
102                                final NexthopManager nexthopManager,
103                                final IMdsalApiManager mdsalManager,
104                                final FibUtil fibUtil) {
105         this.dataBroker = dataBroker;
106         this.nextHopManager = nexthopManager;
107         this.mdsalManager = mdsalManager;
108         this.fibUtil = fibUtil;
109     }
110
111     @Override
112     public void close() {
113         LOG.info("{} closed", getClass().getSimpleName());
114     }
115
116     protected FibUtil getFibUtil() {
117         return fibUtil;
118     }
119
120     protected NexthopManager getNextHopManager() {
121         return nextHopManager;
122     }
123
124     private void addAdjacencyResultToList(List<AdjacencyResult> adjacencyList, AdjacencyResult adjacencyResult) {
125         if (adjacencyResult != null && !adjacencyList.contains(adjacencyResult)) {
126             adjacencyList.add(adjacencyResult);
127         }
128     }
129
130     protected void deleteLocalAdjacency(final BigInteger dpId, final long vpnId, final String ipAddress,
131                               final String ipPrefixAddress) {
132         LOG.trace("deleteLocalAdjacency called with dpid {}, vpnId{}, primaryIpAddress {} currIpPrefix {}",
133                 dpId, vpnId, ipAddress, ipPrefixAddress);
134         try {
135             nextHopManager.removeLocalNextHop(dpId, vpnId, ipAddress, ipPrefixAddress);
136         } catch (NullPointerException e) {
137             LOG.trace("", e);
138         }
139     }
140
141     @Nonnull
142     protected List<AdjacencyResult> resolveAdjacency(final BigInteger remoteDpnId, final long vpnId,
143                                                      final VrfEntry vrfEntry, String rd) {
144         List<RoutePaths> routePaths = vrfEntry.getRoutePaths();
145         FibHelper.sortIpAddress(routePaths);
146         List<AdjacencyResult> adjacencyList = new ArrayList<>();
147         List<String> prefixIpList;
148         LOG.trace("resolveAdjacency called with remotedDpnId {}, vpnId{}, VrfEntry {}",
149                 remoteDpnId, vpnId, vrfEntry);
150         try {
151             if (RouteOrigin.value(vrfEntry.getOrigin()) != RouteOrigin.BGP) {
152                 List<String> usedRds = VpnExtraRouteHelper.getUsedRds(dataBroker, vpnId, vrfEntry.getDestPrefix());
153                 List<Routes> vpnExtraRoutes = VpnExtraRouteHelper.getAllVpnExtraRoutes(dataBroker,
154                         fibUtil.getVpnNameFromId(vpnId), usedRds, vrfEntry.getDestPrefix());
155                 if (vpnExtraRoutes.isEmpty()) {
156                     Prefixes prefixInfo = fibUtil.getPrefixToInterface(vpnId, vrfEntry.getDestPrefix());
157                     /* We don't want to provide an adjacencyList for
158                      * (1) an extra-route-prefix or,
159                      * (2) for a local route without prefix-to-interface.
160                      * Allow only self-imported routes in such cases */
161                     if (prefixInfo == null && FibHelper
162                             .isControllerManagedNonSelfImportedRoute(RouteOrigin.value(vrfEntry.getOrigin()))) {
163                         LOG.debug("The prefix {} in rd {} for vpn {} does not have a valid extra-route or"
164                                 + " prefix-to-interface entry in the data-store", vrfEntry.getDestPrefix(), rd, vpnId);
165                         return adjacencyList;
166                     }
167                     prefixIpList = Collections.singletonList(vrfEntry.getDestPrefix());
168                 } else {
169                     List<String> prefixIpListLocal = new ArrayList<>();
170                     vpnExtraRoutes.forEach(route -> route.getNexthopIpList().forEach(extraRouteIp -> {
171                         String ipPrefix;
172                         if (isIpv4Address(extraRouteIp)) {
173                             ipPrefix = extraRouteIp + NwConstants.IPV4PREFIX;
174                         } else {
175                             ipPrefix = extraRouteIp + NwConstants.IPV6PREFIX;
176                         }
177                         prefixIpListLocal.add(ipPrefix);
178                     }));
179                     prefixIpList = prefixIpListLocal;
180                 }
181             } else {
182                 prefixIpList = Collections.singletonList(vrfEntry.getDestPrefix());
183             }
184
185             for (String prefixIp : prefixIpList) {
186                 if (routePaths == null || routePaths.isEmpty()) {
187                     LOG.trace("Processing Destination IP {} without NextHop IP", prefixIp);
188                     AdjacencyResult adjacencyResult = nextHopManager.getRemoteNextHopPointer(remoteDpnId, vpnId,
189                             prefixIp, null);
190                     addAdjacencyResultToList(adjacencyList, adjacencyResult);
191                     continue;
192                 }
193                 adjacencyList.addAll(routePaths.stream()
194                         .map(routePath -> {
195                             LOG.debug("NextHop IP for destination {} is {}", prefixIp,
196                                     routePath.getNexthopAddress());
197                             return nextHopManager.getRemoteNextHopPointer(remoteDpnId, vpnId,
198                                     prefixIp, routePath.getNexthopAddress());
199                         })
200                         .filter(adjacencyResult -> adjacencyResult != null && !adjacencyList.contains(adjacencyResult))
201                         .distinct()
202                         .collect(toList()));
203             }
204         } catch (NullPointerException e) {
205             LOG.trace("", e);
206         }
207         return adjacencyList;
208     }
209
210     protected void makeConnectedRoute(BigInteger dpId, long vpnId, VrfEntry vrfEntry, String rd,
211                             List<InstructionInfo> instructions, int addOrRemove, WriteTransaction tx,
212                             List<SubTransaction> subTxns) {
213         Boolean wrTxPresent = true;
214         if (tx == null) {
215             wrTxPresent = false;
216             tx = dataBroker.newWriteOnlyTransaction();
217         }
218
219         LOG.trace("makeConnectedRoute: vrfEntry {}", vrfEntry);
220         String[] values = vrfEntry.getDestPrefix().split("/");
221         String ipAddress = values[0];
222         int prefixLength = values.length == 1 ? 0 : Integer.parseInt(values[1]);
223         if (addOrRemove == NwConstants.ADD_FLOW) {
224             LOG.debug("Adding route to DPN {} for rd {} prefix {} ", dpId, rd, vrfEntry.getDestPrefix());
225         } else {
226             LOG.debug("Removing route from DPN {} for rd {} prefix {}", dpId, rd, vrfEntry.getDestPrefix());
227         }
228         InetAddress destPrefix;
229         try {
230             destPrefix = InetAddress.getByName(ipAddress);
231         } catch (UnknownHostException e) {
232             LOG.error("Failed to get destPrefix for prefix {} rd {} VpnId {} DPN {}",
233                     vrfEntry.getDestPrefix(), rd, vpnId, dpId, e);
234             return;
235         }
236
237         List<MatchInfo> matches = new ArrayList<>();
238
239         matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(vpnId), MetaDataUtil.METADATA_MASK_VRFID));
240
241         if (destPrefix instanceof Inet4Address) {
242             matches.add(MatchEthernetType.IPV4);
243             if (prefixLength != 0) {
244                 matches.add(new MatchIpv4Destination(destPrefix.getHostAddress(), Integer.toString(prefixLength)));
245             }
246         } else {
247             matches.add(MatchEthernetType.IPV6);
248             if (prefixLength != 0) {
249                 matches.add(new MatchIpv6Destination(destPrefix.getHostAddress() + "/" + prefixLength));
250             }
251         }
252
253         int priority = DEFAULT_FIB_FLOW_PRIORITY + prefixLength;
254         String flowRef = FibUtil.getFlowRef(dpId, NwConstants.L3_FIB_TABLE, rd, priority, destPrefix);
255         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpId, NwConstants.L3_FIB_TABLE, flowRef, priority,
256                 flowRef, 0, 0,
257                 COOKIE_VM_FIB_TABLE, matches, instructions);
258         Flow flow = flowEntity.getFlowBuilder().build();
259         String flowId = flowEntity.getFlowId();
260         FlowKey flowKey = new FlowKey(new FlowId(flowId));
261         Node nodeDpn = FibUtil.buildDpnNode(dpId);
262
263         InstanceIdentifier<Flow> flowInstanceId = InstanceIdentifier.builder(Nodes.class)
264                 .child(Node.class, nodeDpn.getKey()).augmentation(FlowCapableNode.class)
265                 .child(Table.class, new TableKey(flow.getTableId())).child(Flow.class, flowKey).build();
266
267         if (RouteOrigin.value(vrfEntry.getOrigin()) == RouteOrigin.BGP) {
268             SubTransaction subTransaction = new SubTransactionImpl();
269             if (addOrRemove == NwConstants.ADD_FLOW) {
270                 subTransaction.setInstanceIdentifier(flowInstanceId);
271                 subTransaction.setInstance(flow);
272                 subTransaction.setAction(SubTransaction.CREATE);
273             } else {
274                 subTransaction.setInstanceIdentifier(flowInstanceId);
275                 subTransaction.setAction(SubTransaction.DELETE);
276             }
277             subTxns.add(subTransaction);
278         }
279
280         if (addOrRemove == NwConstants.ADD_FLOW) {
281             tx.put(LogicalDatastoreType.CONFIGURATION, flowInstanceId, flow, true);
282         } else {
283             tx.delete(LogicalDatastoreType.CONFIGURATION, flowInstanceId);
284         }
285
286         if (!wrTxPresent) {
287             tx.submit();
288         }
289     }
290
291     protected void addRewriteDstMacAction(long vpnId, VrfEntry vrfEntry, Prefixes prefixInfo,
292                                         List<ActionInfo> actionInfos) {
293         if (vrfEntry.getMac() != null) {
294             actionInfos.add(new ActionSetFieldEthernetDestination(actionInfos.size(),
295                     new MacAddress(vrfEntry.getMac())));
296             return;
297         }
298         if (prefixInfo == null) {
299             prefixInfo = fibUtil.getPrefixToInterface(vpnId, vrfEntry.getDestPrefix());
300             //Checking PrefixtoInterface again as it is populated later in some cases
301             if (prefixInfo == null) {
302                 LOG.debug("No prefix info found for prefix {}", vrfEntry.getDestPrefix());
303                 return;
304             }
305         }
306         String ipPrefix = prefixInfo.getIpAddress();
307         String ifName = prefixInfo.getVpnInterfaceName();
308         if (ifName == null) {
309             LOG.debug("Failed to get VPN interface for prefix {}", ipPrefix);
310             return;
311         }
312         String vpnName = fibUtil.getVpnNameFromId(vpnId);
313         if (vpnName == null) {
314             LOG.debug("Failed to get VPN name for vpnId {}", vpnId);
315             return;
316         }
317         String macAddress = fibUtil.getMacAddressFromPrefix(ifName, vpnName, ipPrefix);
318         if (macAddress == null) {
319             LOG.warn("No MAC address found for VPN interface {} prefix {}", ifName, ipPrefix);
320             return;
321         }
322         actionInfos.add(new ActionSetFieldEthernetDestination(actionInfos.size(), new MacAddress(macAddress)));
323     }
324
325     protected void addTunnelInterfaceActions(AdjacencyResult adjacencyResult, long vpnId, VrfEntry vrfEntry,
326                                            List<ActionInfo> actionInfos, String rd) {
327         Class<? extends TunnelTypeBase> tunnelType =
328                 VpnExtraRouteHelper.getTunnelType(nextHopManager.getInterfaceManager(),
329                         adjacencyResult.getInterfaceName());
330         if (tunnelType == null) {
331             LOG.debug("Tunnel type not found for vrfEntry {}", vrfEntry);
332             return;
333         }
334         // TODO - For now have added routePath into adjacencyResult so that we know for which
335         // routePath this result is built for. If this is not possible construct a map which does
336         // the same.
337         String nextHopIp = adjacencyResult.getNextHopIp();
338         java.util.Optional<Long> optionalLabel = FibUtil.getLabelForNextHop(vrfEntry, nextHopIp);
339         if (!optionalLabel.isPresent()) {
340             LOG.warn("NextHopIp {} not found in vrfEntry {}", nextHopIp, vrfEntry);
341             return;
342         }
343         long label = optionalLabel.get();
344         BigInteger tunnelId = null;
345         Prefixes prefixInfo = null;
346         // FIXME vxlan vni bit set is not working properly with OVS.need to
347         // revisit
348         if (tunnelType.equals(TunnelTypeVxlan.class)) {
349             if (FibHelper.isControllerManagedNonSelfImportedRoute(RouteOrigin.value(vrfEntry.getOrigin()))) {
350                 prefixInfo = fibUtil.getPrefixToInterface(vpnId, vrfEntry.getDestPrefix());
351                 //For extra route, the prefixInfo is fetched from the primary adjacency
352                 if (prefixInfo == null) {
353                     prefixInfo = fibUtil.getPrefixToInterface(vpnId, adjacencyResult.getPrefix());
354                 }
355             } else {
356                 //Imported Route. Get Prefix Info from parent RD
357                 VpnInstanceOpDataEntry parentVpn =  fibUtil.getVpnInstance(vrfEntry.getParentVpnRd());
358                 prefixInfo = fibUtil.getPrefixToInterface(parentVpn.getVpnId(), adjacencyResult.getPrefix());
359             }
360             // Internet VPN VNI will be used as tun_id for NAT use-cases
361             if (Prefixes.PrefixCue.Nat.equals(prefixInfo.getPrefixCue())) {
362                 if (vrfEntry.getL3vni() != null && vrfEntry.getL3vni() != 0) {
363                     tunnelId = BigInteger.valueOf(vrfEntry.getL3vni());
364                 }
365             } else {
366                 if (fibUtil.enforceVxlanDatapathSemanticsforInternalRouterVpn(prefixInfo.getSubnetId(), vpnId,
367                         rd)) {
368                     java.util.Optional<Long> optionalVni = fibUtil.getVniForVxlanNetwork(prefixInfo.getSubnetId());
369                     if (!optionalVni.isPresent()) {
370                         LOG.error("VNI not found for nexthop {} vrfEntry {} with subnetId {}", nextHopIp,
371                                 vrfEntry, prefixInfo.getSubnetId());
372                         return;
373                     }
374                     tunnelId = BigInteger.valueOf(optionalVni.get());
375                 } else {
376                     tunnelId = BigInteger.valueOf(label);
377                 }
378             }
379         } else {
380             tunnelId = BigInteger.valueOf(label);
381         }
382         LOG.debug("adding set tunnel id action for label {}", label);
383         actionInfos.add(new ActionSetFieldTunnelId(tunnelId));
384         addRewriteDstMacAction(vpnId, vrfEntry, prefixInfo, actionInfos);
385     }
386
387     public void programRemoteFib(final BigInteger remoteDpnId, final long vpnId,
388                                   final VrfEntry vrfEntry, WriteTransaction tx, String rd,
389                                   List<AdjacencyResult> adjacencyResults,
390                                   List<SubTransaction> subTxns) {
391         List<InstructionInfo> instructions = new ArrayList<>();
392         for (AdjacencyResult adjacencyResult : adjacencyResults) {
393             List<ActionInfo> actionInfos = new ArrayList<>();
394             String egressInterface = adjacencyResult.getInterfaceName();
395             if (FibUtil.isTunnelInterface(adjacencyResult)) {
396                 addTunnelInterfaceActions(adjacencyResult, vpnId, vrfEntry, actionInfos, rd);
397             } else {
398                 addRewriteDstMacAction(vpnId, vrfEntry, null, actionInfos);
399             }
400             List<ActionInfo> egressActions = nextHopManager.getEgressActionsForInterface(egressInterface,
401                     actionInfos.size());
402             if (egressActions.isEmpty()) {
403                 LOG.error(
404                         "Failed to retrieve egress action for prefix {} route-paths {} interface {}. "
405                                 + "Aborting remote FIB entry creation.",
406                         vrfEntry.getDestPrefix(), vrfEntry.getRoutePaths(), egressInterface);
407                 return;
408             }
409             actionInfos.addAll(egressActions);
410             instructions.add(new InstructionApplyActions(actionInfos));
411         }
412         makeConnectedRoute(remoteDpnId, vpnId, vrfEntry, rd, instructions, NwConstants.ADD_FLOW, tx, subTxns);
413     }
414
415     public boolean checkDpnDeleteFibEntry(VpnNexthop localNextHopInfo, BigInteger remoteDpnId, long vpnId,
416                                            VrfEntry vrfEntry, String rd,
417                                            WriteTransaction tx, List<SubTransaction> subTxns) {
418         boolean isRemoteRoute = true;
419         if (localNextHopInfo != null) {
420             isRemoteRoute = !remoteDpnId.equals(localNextHopInfo.getDpnId());
421         }
422         if (isRemoteRoute) {
423             makeConnectedRoute(remoteDpnId, vpnId, vrfEntry, rd, null, NwConstants.DEL_FLOW, tx, subTxns);
424             LOG.debug("Successfully delete FIB entry: vrfEntry={}, vpnId={}", vrfEntry.getDestPrefix(), vpnId);
425             return true;
426         } else {
427             LOG.debug("Did not delete FIB entry: rd={}, vrfEntry={}, as it is local to dpnId={}",
428                     rd, vrfEntry.getDestPrefix(), remoteDpnId);
429             return false;
430         }
431     }
432
433     public void deleteRemoteRoute(final BigInteger localDpnId, final BigInteger remoteDpnId,
434                                   final long vpnId, final VrfTablesKey vrfTableKey,
435                                   final VrfEntry vrfEntry, Optional<Routes> extraRouteOptional,
436                                   WriteTransaction tx) {
437
438         Boolean wrTxPresent = true;
439         if (tx == null) {
440             wrTxPresent = false;
441             tx = dataBroker.newWriteOnlyTransaction();
442         }
443
444         LOG.debug("deleting remote route: prefix={}, vpnId={} localDpnId {} remoteDpnId {}",
445                 vrfEntry.getDestPrefix(), vpnId, localDpnId, remoteDpnId);
446         String rd = vrfTableKey.getRouteDistinguisher();
447
448         if (localDpnId != null && localDpnId != BigInteger.ZERO) {
449             // localDpnId is not known when clean up happens for last vm for a vpn on a dpn
450             if (extraRouteOptional.isPresent()) {
451                 nextHopManager.setupLoadBalancingNextHop(vpnId, remoteDpnId, vrfEntry.getDestPrefix(),
452                         Collections.emptyList() /*listBucketInfo*/ , false);
453             }
454             makeConnectedRoute(remoteDpnId, vpnId, vrfEntry, rd, null, NwConstants.DEL_FLOW, tx, null);
455             LOG.debug("Successfully delete FIB entry: vrfEntry={}, vpnId={}", vrfEntry.getDestPrefix(), vpnId);
456             return;
457         }
458
459         // below two reads are kept as is, until best way is found to identify dpnID
460         VpnNexthop localNextHopInfo = nextHopManager.getVpnNexthop(vpnId, vrfEntry.getDestPrefix());
461         if (extraRouteOptional.isPresent()) {
462             nextHopManager.setupLoadBalancingNextHop(vpnId, remoteDpnId, vrfEntry.getDestPrefix(),
463                     Collections.emptyList() /*listBucketInfo*/ , false);
464         } else {
465             checkDpnDeleteFibEntry(localNextHopInfo, remoteDpnId, vpnId, vrfEntry, rd, tx, null);
466         }
467         if (!wrTxPresent) {
468             tx.submit();
469         }
470     }
471
472     public static InstanceIdentifier<Routes> getVpnToExtrarouteIdentifier(String vpnName, String vrfId,
473                                                                     String ipPrefix) {
474         return InstanceIdentifier.builder(VpnToExtraroutes.class)
475                 .child(Vpn.class, new VpnKey(vpnName)).child(ExtraRoutes.class,
476                         new ExtraRoutesKey(vrfId)).child(Routes.class, new RoutesKey(ipPrefix)).build();
477     }
478
479     public Routes getVpnToExtraroute(Long vpnId, String vpnRd, String destPrefix) {
480         String optVpnName = fibUtil.getVpnNameFromId(vpnId);
481         if (optVpnName != null) {
482             InstanceIdentifier<Routes> vpnExtraRoutesId = getVpnToExtrarouteIdentifier(
483                     optVpnName, vpnRd, destPrefix);
484             return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, vpnExtraRoutesId).orNull();
485         }
486         return null;
487     }
488
489     public FlowEntity buildL3vpnGatewayFlow(BigInteger dpId, String gwMacAddress, long vpnId) {
490         List<MatchInfo> mkMatches = new ArrayList<>();
491         mkMatches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(vpnId), MetaDataUtil.METADATA_MASK_VRFID));
492         mkMatches.add(new MatchEthernetDestination(new MacAddress(gwMacAddress)));
493         List<InstructionInfo> mkInstructions = new ArrayList<>();
494         mkInstructions.add(new InstructionGotoTable(NwConstants.L3_FIB_TABLE));
495         String flowId = FibUtil.getL3VpnGatewayFlowRef(NwConstants.L3_GW_MAC_TABLE, dpId, vpnId, gwMacAddress);
496         return MDSALUtil.buildFlowEntity(dpId, NwConstants.L3_GW_MAC_TABLE,
497                 flowId, 20, flowId, 0, 0, NwConstants.COOKIE_L3_GW_MAC_TABLE, mkMatches, mkInstructions);
498     }
499
500     public void installPingResponderFlowEntry(BigInteger dpnId, long vpnId, String routerInternalIp,
501                                               MacAddress routerMac, long label, int addOrRemove) {
502
503         List<MatchInfo> matches = new ArrayList<>();
504         matches.add(MatchIpProtocol.ICMP);
505         matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(vpnId), MetaDataUtil.METADATA_MASK_VRFID));
506         matches.add(new MatchIcmpv4((short) 8, (short) 0));
507         matches.add(MatchEthernetType.IPV4);
508         matches.add(new MatchIpv4Destination(routerInternalIp, "32"));
509
510         List<ActionInfo> actionsInfos = new ArrayList<>();
511
512         // Set Eth Src and Eth Dst
513         actionsInfos.add(new ActionMoveSourceDestinationEth());
514         actionsInfos.add(new ActionSetFieldEthernetSource(routerMac));
515
516         // Move Ip Src to Ip Dst
517         actionsInfos.add(new ActionMoveSourceDestinationIp());
518         actionsInfos.add(new ActionSetSourceIp(routerInternalIp, "32"));
519
520         // Set the ICMP type to 0 (echo reply)
521         actionsInfos.add(new ActionSetIcmpType((short) 0));
522
523         actionsInfos.add(new ActionNxLoadInPort(BigInteger.ZERO));
524
525         actionsInfos.add(new ActionNxResubmit(NwConstants.L3_FIB_TABLE));
526
527         List<InstructionInfo> instructions = new ArrayList<>();
528
529         instructions.add(new InstructionApplyActions(actionsInfos));
530
531         int priority = FibConstants.DEFAULT_FIB_FLOW_PRIORITY + FibConstants.DEFAULT_PREFIX_LENGTH;
532         String flowRef = FibUtil.getFlowRef(dpnId, NwConstants.L3_FIB_TABLE, label, priority);
533
534         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpnId, NwConstants.L3_FIB_TABLE, flowRef, priority, flowRef,
535                 0, 0, NwConstants.COOKIE_VM_FIB_TABLE, matches, instructions);
536
537         if (addOrRemove == NwConstants.ADD_FLOW) {
538             mdsalManager.syncInstallFlow(flowEntity);
539         } else {
540             mdsalManager.syncRemoveFlow(flowEntity);
541         }
542     }
543 }