Upgrade: wait for interface states for adjacencies
[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 = fibUtil.getMacAddressFromPrefix(ifName, vpnName, ipPrefix);
339         if (macAddress == null) {
340             LOG.warn("No MAC address found for VPN interface {} prefix {}", ifName, ipPrefix);
341             return;
342         }
343         actionInfos.add(new ActionSetFieldEthernetDestination(actionInfos.size(), new MacAddress(macAddress)));
344     }
345
346     protected void addTunnelInterfaceActions(AdjacencyResult adjacencyResult, long vpnId, VrfEntry vrfEntry,
347                                            List<ActionInfo> actionInfos, String rd) {
348         Class<? extends TunnelTypeBase> tunnelType =
349                 VpnExtraRouteHelper.getTunnelType(nextHopManager.getItmManager(), adjacencyResult.getInterfaceName());
350         if (tunnelType == null) {
351             LOG.debug("Tunnel type not found for vrfEntry {}", vrfEntry);
352             return;
353         }
354         // TODO - For now have added routePath into adjacencyResult so that we know for which
355         // routePath this result is built for. If this is not possible construct a map which does
356         // the same.
357         String nextHopIp = adjacencyResult.getNextHopIp();
358         java.util.Optional<Long> optionalLabel = FibUtil.getLabelForNextHop(vrfEntry, nextHopIp);
359         if (!optionalLabel.isPresent()) {
360             LOG.warn("NextHopIp {} not found in vrfEntry {}", nextHopIp, vrfEntry);
361             return;
362         }
363         long label = optionalLabel.get();
364         BigInteger tunnelId = null;
365         Prefixes prefixInfo = null;
366         // FIXME vxlan vni bit set is not working properly with OVS.need to
367         // revisit
368         if (tunnelType.equals(TunnelTypeVxlan.class)) {
369             if (FibHelper.isControllerManagedNonSelfImportedRoute(RouteOrigin.value(vrfEntry.getOrigin()))) {
370                 prefixInfo = fibUtil.getPrefixToInterface(vpnId, vrfEntry.getDestPrefix());
371                 //For extra route, the prefixInfo is fetched from the primary adjacency
372                 if (prefixInfo == null) {
373                     prefixInfo = fibUtil.getPrefixToInterface(vpnId, adjacencyResult.getPrefix());
374                 }
375             } else {
376                 //Imported Route. Get Prefix Info from parent RD
377                 VpnInstanceOpDataEntry parentVpn =  fibUtil.getVpnInstance(vrfEntry.getParentVpnRd());
378                 prefixInfo = fibUtil.getPrefixToInterface(parentVpn.getVpnId(), adjacencyResult.getPrefix());
379             }
380             // Internet VPN VNI will be used as tun_id for NAT use-cases
381             if (Prefixes.PrefixCue.Nat.equals(prefixInfo.getPrefixCue())) {
382                 if (vrfEntry.getL3vni() != null && vrfEntry.getL3vni() != 0) {
383                     tunnelId = BigInteger.valueOf(vrfEntry.getL3vni());
384                 }
385             } else {
386                 if (fibUtil.enforceVxlanDatapathSemanticsforInternalRouterVpn(prefixInfo.getSubnetId(), vpnId,
387                         rd)) {
388                     java.util.Optional<Long> optionalVni = fibUtil.getVniForVxlanNetwork(prefixInfo.getSubnetId());
389                     if (!optionalVni.isPresent()) {
390                         LOG.error("VNI not found for nexthop {} vrfEntry {} with subnetId {}", nextHopIp,
391                                 vrfEntry, prefixInfo.getSubnetId());
392                         return;
393                     }
394                     tunnelId = BigInteger.valueOf(optionalVni.get());
395                 } else {
396                     tunnelId = BigInteger.valueOf(label);
397                 }
398             }
399         } else {
400             tunnelId = BigInteger.valueOf(label);
401         }
402         LOG.debug("adding set tunnel id action for label {}", label);
403         actionInfos.add(new ActionSetFieldTunnelId(tunnelId));
404         addRewriteDstMacAction(vpnId, vrfEntry, prefixInfo, actionInfos);
405     }
406
407     private InstanceIdentifier<Interface> getFirstAbsentInterfaceStateIid(List<AdjacencyResult> adjacencyResults) {
408         InstanceIdentifier<Interface> res = null;
409         for (AdjacencyResult adjacencyResult : adjacencyResults) {
410             String interfaceName = adjacencyResult.getInterfaceName();
411             if (null == fibUtil.getInterfaceStateFromOperDS(interfaceName)) {
412                 res = fibUtil.buildStateInterfaceId(interfaceName);
413                 break;
414             }
415         }
416
417         return res;
418     }
419
420     public void programRemoteFib(final BigInteger remoteDpnId, final long vpnId,
421                                   final VrfEntry vrfEntry, WriteTransaction tx, String rd,
422                                   List<AdjacencyResult> adjacencyResults,
423                                   List<SubTransaction> subTxns) {
424         if (upgradeState.isUpgradeInProgress()) {
425             InstanceIdentifier<Interface> absentInterfaceStateIid = getFirstAbsentInterfaceStateIid(adjacencyResults);
426             if (absentInterfaceStateIid != null) {
427                 LOG.info("programRemoteFib: interface state for {} not yet present, waiting...",
428                          absentInterfaceStateIid);
429                 eventCallbacks.onAddOrUpdate(LogicalDatastoreType.OPERATIONAL,
430                     absentInterfaceStateIid,
431                     (before, after) -> {
432                         LOG.info("programRemoteFib: waited for and got interface state {}", absentInterfaceStateIid);
433                         txRunner.callWithNewWriteOnlyTransactionAndSubmit((wtx) -> {
434                             programRemoteFib(remoteDpnId, vpnId, vrfEntry, wtx, rd, adjacencyResults, null);
435                         });
436                         return DataTreeEventCallbackRegistrar.NextAction.UNREGISTER;
437                     },
438                     Duration.of(15, ChronoUnit.MINUTES),
439                     (iid) -> {
440                         LOG.error("programRemoteFib: timed out waiting for {}", absentInterfaceStateIid);
441                         txRunner.callWithNewWriteOnlyTransactionAndSubmit((wtx) -> {
442                             programRemoteFib(remoteDpnId, vpnId, vrfEntry, wtx, rd, adjacencyResults, null);
443                         });
444                     });
445                 return;
446             }
447         }
448
449         List<InstructionInfo> instructions = new ArrayList<>();
450         for (AdjacencyResult adjacencyResult : adjacencyResults) {
451             List<ActionInfo> actionInfos = new ArrayList<>();
452             String egressInterface = adjacencyResult.getInterfaceName();
453             if (FibUtil.isTunnelInterface(adjacencyResult)) {
454                 addTunnelInterfaceActions(adjacencyResult, vpnId, vrfEntry, actionInfos, rd);
455             } else {
456                 addRewriteDstMacAction(vpnId, vrfEntry, null, actionInfos);
457             }
458             List<ActionInfo> egressActions = nextHopManager.getEgressActionsForInterface(egressInterface,
459                     actionInfos.size(), true);
460             if (egressActions.isEmpty()) {
461                 LOG.error(
462                         "Failed to retrieve egress action for prefix {} route-paths {} interface {}. "
463                                 + "Aborting remote FIB entry creation.",
464                         vrfEntry.getDestPrefix(), vrfEntry.getRoutePaths(), egressInterface);
465                 return;
466             }
467             actionInfos.addAll(egressActions);
468             instructions.add(new InstructionApplyActions(actionInfos));
469         }
470         makeConnectedRoute(remoteDpnId, vpnId, vrfEntry, rd, instructions, NwConstants.ADD_FLOW, tx, subTxns);
471     }
472
473     public boolean checkDpnDeleteFibEntry(VpnNexthop localNextHopInfo, BigInteger remoteDpnId, long vpnId,
474                                            VrfEntry vrfEntry, String rd,
475                                            WriteTransaction tx, List<SubTransaction> subTxns) {
476         boolean isRemoteRoute = true;
477         if (localNextHopInfo != null) {
478             isRemoteRoute = !remoteDpnId.equals(localNextHopInfo.getDpnId());
479         }
480         if (isRemoteRoute) {
481             makeConnectedRoute(remoteDpnId, vpnId, vrfEntry, rd, null, NwConstants.DEL_FLOW, tx, subTxns);
482             LOG.debug("Successfully delete FIB entry: vrfEntry={}, vpnId={}", vrfEntry.getDestPrefix(), vpnId);
483             return true;
484         } else {
485             LOG.debug("Did not delete FIB entry: rd={}, vrfEntry={}, as it is local to dpnId={}",
486                     rd, vrfEntry.getDestPrefix(), remoteDpnId);
487             return false;
488         }
489     }
490
491     public void deleteRemoteRoute(final BigInteger localDpnId, final BigInteger remoteDpnId,
492                                   final long vpnId, final VrfTablesKey vrfTableKey,
493                                   final VrfEntry vrfEntry, Optional<Routes> extraRouteOptional,
494                                   WriteTransaction tx) {
495         if (tx == null) {
496             ListenableFutures.addErrorLogging(txRunner.callWithNewWriteOnlyTransactionAndSubmit(
497                 newTx -> deleteRemoteRoute(localDpnId, remoteDpnId, vpnId, vrfTableKey, vrfEntry,
498                         extraRouteOptional, newTx)), LOG, "Error deleting remote route");
499             return;
500         }
501
502         LOG.debug("deleting remote route: prefix={}, vpnId={} localDpnId {} remoteDpnId {}",
503                 vrfEntry.getDestPrefix(), vpnId, localDpnId, remoteDpnId);
504         String rd = vrfTableKey.getRouteDistinguisher();
505
506         if (localDpnId != null && localDpnId != BigInteger.ZERO) {
507             // localDpnId is not known when clean up happens for last vm for a vpn on a dpn
508             if (extraRouteOptional.isPresent()) {
509                 nextHopManager.setupLoadBalancingNextHop(vpnId, remoteDpnId, vrfEntry.getDestPrefix(),
510                         Collections.emptyList() /*listBucketInfo*/ , false);
511             }
512             makeConnectedRoute(remoteDpnId, vpnId, vrfEntry, rd, null, NwConstants.DEL_FLOW, tx, null);
513             LOG.debug("Successfully delete FIB entry: vrfEntry={}, vpnId={}", vrfEntry.getDestPrefix(), vpnId);
514             return;
515         }
516
517         // below two reads are kept as is, until best way is found to identify dpnID
518         VpnNexthop localNextHopInfo = nextHopManager.getVpnNexthop(vpnId, vrfEntry.getDestPrefix());
519         if (extraRouteOptional.isPresent()) {
520             nextHopManager.setupLoadBalancingNextHop(vpnId, remoteDpnId, vrfEntry.getDestPrefix(),
521                     Collections.emptyList() /*listBucketInfo*/ , false);
522         } else {
523             checkDpnDeleteFibEntry(localNextHopInfo, remoteDpnId, vpnId, vrfEntry, rd, tx, null);
524         }
525     }
526
527     public static InstanceIdentifier<Routes> getVpnToExtrarouteIdentifier(String vpnName, String vrfId,
528                                                                     String ipPrefix) {
529         return InstanceIdentifier.builder(VpnToExtraroutes.class)
530                 .child(Vpn.class, new VpnKey(vpnName)).child(ExtraRoutes.class,
531                         new ExtraRoutesKey(vrfId)).child(Routes.class, new RoutesKey(ipPrefix)).build();
532     }
533
534     public Routes getVpnToExtraroute(Long vpnId, String vpnRd, String destPrefix) {
535         String optVpnName = fibUtil.getVpnNameFromId(vpnId);
536         if (optVpnName != null) {
537             InstanceIdentifier<Routes> vpnExtraRoutesId = getVpnToExtrarouteIdentifier(
538                     optVpnName, vpnRd, destPrefix);
539             return MDSALUtil.read(dataBroker, LogicalDatastoreType.OPERATIONAL, vpnExtraRoutesId).orNull();
540         }
541         return null;
542     }
543
544     public FlowEntity buildL3vpnGatewayFlow(BigInteger dpId, String gwMacAddress, long vpnId) {
545         List<MatchInfo> mkMatches = new ArrayList<>();
546         mkMatches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(vpnId), MetaDataUtil.METADATA_MASK_VRFID));
547         mkMatches.add(new MatchEthernetDestination(new MacAddress(gwMacAddress)));
548         List<InstructionInfo> mkInstructions = new ArrayList<>();
549         mkInstructions.add(new InstructionGotoTable(NwConstants.L3_FIB_TABLE));
550         String flowId = FibUtil.getL3VpnGatewayFlowRef(NwConstants.L3_GW_MAC_TABLE, dpId, vpnId, gwMacAddress);
551         return MDSALUtil.buildFlowEntity(dpId, NwConstants.L3_GW_MAC_TABLE,
552                 flowId, 20, flowId, 0, 0, NwConstants.COOKIE_L3_GW_MAC_TABLE, mkMatches, mkInstructions);
553     }
554
555     public void installPingResponderFlowEntry(BigInteger dpnId, long vpnId, String routerInternalIp,
556                                               MacAddress routerMac, long label, int addOrRemove) {
557
558         List<MatchInfo> matches = new ArrayList<>();
559         matches.add(MatchIpProtocol.ICMP);
560         matches.add(new MatchMetadata(MetaDataUtil.getVpnIdMetadata(vpnId), MetaDataUtil.METADATA_MASK_VRFID));
561         matches.add(new MatchIcmpv4((short) 8, (short) 0));
562         matches.add(MatchEthernetType.IPV4);
563         matches.add(new MatchIpv4Destination(routerInternalIp, "32"));
564
565         List<ActionInfo> actionsInfos = new ArrayList<>();
566
567         // Set Eth Src and Eth Dst
568         actionsInfos.add(new ActionMoveSourceDestinationEth());
569         actionsInfos.add(new ActionSetFieldEthernetSource(routerMac));
570
571         // Move Ip Src to Ip Dst
572         actionsInfos.add(new ActionMoveSourceDestinationIp());
573         actionsInfos.add(new ActionSetSourceIp(routerInternalIp, "32"));
574
575         // Set the ICMP type to 0 (echo reply)
576         actionsInfos.add(new ActionSetIcmpType((short) 0));
577
578         actionsInfos.add(new ActionNxLoadInPort(BigInteger.ZERO));
579
580         actionsInfos.add(new ActionNxResubmit(NwConstants.L3_FIB_TABLE));
581
582         List<InstructionInfo> instructions = new ArrayList<>();
583
584         instructions.add(new InstructionApplyActions(actionsInfos));
585
586         int priority = FibConstants.DEFAULT_FIB_FLOW_PRIORITY + FibConstants.DEFAULT_PREFIX_LENGTH;
587         String flowRef = FibUtil.getFlowRef(dpnId, NwConstants.L3_FIB_TABLE, label, priority);
588
589         FlowEntity flowEntity = MDSALUtil.buildFlowEntity(dpnId, NwConstants.L3_FIB_TABLE, flowRef, priority, flowRef,
590                 0, 0, NwConstants.COOKIE_VM_FIB_TABLE, matches, instructions);
591
592         if (addOrRemove == NwConstants.ADD_FLOW) {
593             mdsalManager.syncInstallFlow(flowEntity);
594         } else {
595             mdsalManager.syncRemoveFlow(flowEntity);
596         }
597     }
598 }