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