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