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