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