2 * Copyright (c) 2015 - 2016 Ericsson India Global Services Pvt Ltd. and others. All rights reserved.
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
8 package org.opendaylight.vpnservice.fibmanager;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
15 import java.math.BigInteger;
16 import java.net.InetAddress;
17 import java.net.UnknownHostException;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.List;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.Future;
24 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
25 import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
26 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
27 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
28 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
29 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
30 import org.opendaylight.vpnmanager.api.IVpnManager;
31 import org.opendaylight.vpnservice.mdsalutil.AbstractDataChangeListener;
32 import org.opendaylight.vpnservice.itm.globals.ITMConstants;
33 import org.opendaylight.vpnservice.mdsalutil.ActionInfo;
34 import org.opendaylight.vpnservice.mdsalutil.ActionType;
35 import org.opendaylight.vpnservice.mdsalutil.FlowEntity;
36 import org.opendaylight.vpnservice.mdsalutil.InstructionInfo;
37 import org.opendaylight.vpnservice.mdsalutil.InstructionType;
38 import org.opendaylight.vpnservice.mdsalutil.MDSALUtil;
39 import org.opendaylight.vpnservice.mdsalutil.MatchFieldType;
40 import org.opendaylight.vpnservice.mdsalutil.MatchInfo;
41 import org.opendaylight.vpnservice.mdsalutil.MetaDataUtil;
42 import org.opendaylight.vpnservice.mdsalutil.NwConstants;
43 import org.opendaylight.vpnservice.mdsalutil.interfaces.IMdsalApiManager;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.PrefixToInterface;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.VpnInstanceOpData;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.prefix.to._interface.VpnIds;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.prefix.to._interface.VpnIdsKey;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.prefix.to._interface.vpn.ids.Prefixes;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.prefix.to._interface.vpn.ids.PrefixesKey;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntryKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.l3vpn.rev130911.vpn.instance.op.data.vpn.instance.op.data.entry.VpnToDpnList;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.overlay.rev150105.TunnelTypeVxlan;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.itm.rpcs.rev151217.ItmRpcService;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.FibEntries;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.fibentries.VrfTables;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.fibentries.VrfTablesKey;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.fibmanager.rev150330.vrfentries.VrfEntry;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.TunnelTypeBase;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rev150331.TunnelTypeMplsOverGre;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetEgressActionsForInterfaceInputBuilder;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetEgressActionsForInterfaceOutput;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetTunnelTypeInputBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.GetTunnelTypeOutput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.interfacemgr.rpcs.rev151003.OdlInterfaceRpcService;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.vpnservice.l3nexthop.rev150409.l3nexthop.vpnnexthops.VpnNexthop;
67 import org.opendaylight.yangtools.concepts.ListenerRegistration;
68 import org.opendaylight.yangtools.yang.binding.DataObject;
69 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
70 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder;
71 import org.opendaylight.yangtools.yang.common.RpcResult;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
75 public class FibManager extends AbstractDataChangeListener<VrfEntry> implements AutoCloseable{
76 private static final Logger LOG = LoggerFactory.getLogger(FibManager.class);
77 private static final String FLOWID_PREFIX = "L3.";
78 private ListenerRegistration<DataChangeListener> listenerRegistration;
79 private final DataBroker broker;
80 private IMdsalApiManager mdsalManager;
81 private IVpnManager vpnmanager;
82 private NexthopManager nextHopManager;
83 private ItmRpcService itmManager;
84 private OdlInterfaceRpcService interfaceManager;
86 private static final short L3_FIB_TABLE = 21;
87 private static final short L3_LFIB_TABLE = 20;
88 public static final short INTERNAL_TUNNEL_TABLE = 23;
89 private static final short L3_PROTOCOL_TABLE = 36;
90 private static final short L3_INTERFACE_TABLE = 80;
91 public static final short LPORT_DISPATCHER_TABLE = 30;
92 private static final BigInteger COOKIE_VM_LFIB_TABLE = new BigInteger("8000002", 16);
93 private static final BigInteger COOKIE_VM_FIB_TABLE = new BigInteger("8000003", 16);
94 private static final int DEFAULT_FIB_FLOW_PRIORITY = 10;
95 private static final BigInteger METADATA_MASK_CLEAR = new BigInteger("000000FFFFFFFFFF", 16);
96 private static final BigInteger CLEAR_METADATA = BigInteger.valueOf(0);
97 public static final BigInteger COOKIE_TUNNEL = new BigInteger("9000000", 16);
100 private static final FutureCallback<Void> DEFAULT_CALLBACK =
101 new FutureCallback<Void>() {
102 public void onSuccess(Void result) {
103 LOG.debug("Success in Datastore write operation");
106 public void onFailure(Throwable error) {
107 LOG.error("Error in Datastore write operation", error);
111 public FibManager(final DataBroker db) {
112 super(VrfEntry.class);
114 registerListener(db);
118 public void close() throws Exception {
119 if (listenerRegistration != null) {
121 listenerRegistration.close();
122 } catch (final Exception e) {
123 LOG.error("Error when cleaning up DataChangeListener.", e);
125 listenerRegistration = null;
127 LOG.info("Fib Manager Closed");
130 public void setNextHopManager(NexthopManager nextHopManager) {
131 this.nextHopManager = nextHopManager;
134 public void setMdsalManager(IMdsalApiManager mdsalManager) {
135 this.mdsalManager = mdsalManager;
138 public void setVpnmanager(IVpnManager vpnmanager) {
139 this.vpnmanager = vpnmanager;
142 public void setITMRpcService(ItmRpcService itmManager) {
143 this.itmManager = itmManager;
146 public void setInterfaceManager(OdlInterfaceRpcService ifManager) {
147 this.interfaceManager = ifManager;
150 private void registerListener(final DataBroker db) {
152 listenerRegistration = db.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL,
153 getWildCardPath(), FibManager.this, DataChangeScope.SUBTREE);
154 } catch (final Exception e) {
155 LOG.error("FibManager DataChange listener registration fail!", e);
156 throw new IllegalStateException("FibManager registration Listener failed.", e);
160 private <T extends DataObject> Optional<T> read(LogicalDatastoreType datastoreType,
161 InstanceIdentifier<T> path) {
163 ReadOnlyTransaction tx = broker.newReadOnlyTransaction();
165 Optional<T> result = Optional.absent();
167 result = tx.read(datastoreType, path).get();
168 } catch (Exception e) {
169 throw new RuntimeException(e);
175 private InstanceIdentifier<VrfEntry> getWildCardPath() {
176 return InstanceIdentifier.create(FibEntries.class).child(VrfTables.class).child(VrfEntry.class);
179 private <T extends DataObject> void asyncWrite(LogicalDatastoreType datastoreType,
180 InstanceIdentifier<T> path, T data, FutureCallback<Void> callback) {
181 WriteTransaction tx = broker.newWriteOnlyTransaction();
182 tx.put(datastoreType, path, data, true);
183 Futures.addCallback(tx.submit(), callback);
187 protected void add(final InstanceIdentifier<VrfEntry> identifier,
188 final VrfEntry vrfEntry) {
189 LOG.trace("key: " + identifier + ", value=" + vrfEntry );
190 createFibEntries(identifier, vrfEntry);
194 protected void remove(InstanceIdentifier<VrfEntry> identifier, VrfEntry vrfEntry) {
195 LOG.trace("key: " + identifier + ", value=" + vrfEntry);
196 deleteFibEntries(identifier, vrfEntry);
200 protected void update(InstanceIdentifier<VrfEntry> identifier, VrfEntry original, VrfEntry update) {
201 LOG.trace("key: " + identifier + ", original=" + original + ", update=" + update );
202 createFibEntries(identifier, update);
205 private void createFibEntries(final InstanceIdentifier<VrfEntry> identifier,
206 final VrfEntry vrfEntry) {
207 final VrfTablesKey vrfTableKey = identifier.firstKeyOf(VrfTables.class, VrfTablesKey.class);
208 Preconditions.checkNotNull(vrfTableKey, "VrfTablesKey cannot be null or empty!");
209 Preconditions.checkNotNull(vrfEntry, "VrfEntry cannot be null or empty!");
211 VpnInstanceOpDataEntry vpnInstance = getVpnInstance(vrfTableKey.getRouteDistinguisher());
212 Preconditions.checkNotNull(vpnInstance, "Vpn Instance not available!");
213 Preconditions.checkNotNull(vpnInstance.getVpnId(), "Vpn Instance with rd " + vpnInstance.getVrfId() + "has null vpnId!");
215 Collection<VpnToDpnList> vpnToDpnList = vpnInstance.getVpnToDpnList();
216 if (vpnToDpnList != null) {
217 BigInteger localDpnId = createLocalFibEntry(vpnInstance.getVpnId(),
218 vrfTableKey.getRouteDistinguisher(), vrfEntry);
219 for (VpnToDpnList curDpn : vpnToDpnList) {
220 if (!curDpn.getDpnId().equals(localDpnId)) {
221 createRemoteFibEntry(localDpnId, curDpn.getDpnId(), vpnInstance.getVpnId(),
222 vrfTableKey, vrfEntry);
228 public BigInteger createLocalFibEntry(Long vpnId, String rd, VrfEntry vrfEntry) {
229 BigInteger localDpnId = BigInteger.ZERO;
230 Prefixes localNextHopInfo = getPrefixToInterface(vpnId, vrfEntry.getDestPrefix());
231 boolean staticRoute = false;
233 //If the vrf entry is a static/extra route, the nexthop of the entry would be a adjacency in the vpn
234 if(localNextHopInfo == null) {
235 localNextHopInfo = getPrefixToInterface(vpnId, vrfEntry.getNextHopAddress() + "/32");
239 if(localNextHopInfo != null) {
240 localDpnId = localNextHopInfo.getDpnId();
241 long groupId = nextHopManager.createLocalNextHop(vpnId, localDpnId, localNextHopInfo.getVpnInterfaceName(),
242 (staticRoute == true) ? vrfEntry.getNextHopAddress() + "/32" : vrfEntry.getDestPrefix());
243 List<ActionInfo> actionInfos = new ArrayList<ActionInfo>();
245 actionInfos.add(new ActionInfo(ActionType.group, new String[] { String.valueOf(groupId)}));
247 makeConnectedRoute(localDpnId, vpnId, vrfEntry, rd, actionInfos, NwConstants.ADD_FLOW);
248 makeLFibTableEntry(localDpnId, vrfEntry.getLabel(), groupId, vrfEntry.getNextHopAddress(), NwConstants.ADD_FLOW);
250 LOG.debug("Installing tunnel table entry on dpn {} for interface {} with label {}",
251 localDpnId, localNextHopInfo.getVpnInterfaceName(), vrfEntry.getLabel());
252 makeTunnelTableEntry(localDpnId, vrfEntry.getLabel(), groupId);
258 private void makeTunnelTableEntry(BigInteger dpId, long label, long groupId/*String egressInterfaceName*/) {
259 List<ActionInfo> actionsInfos = new ArrayList<ActionInfo>();
260 actionsInfos.add(new ActionInfo(ActionType.group, new String[] { String.valueOf(groupId) }));
263 createTerminatingServiceActions(dpId, (int)label, actionsInfos);
265 LOG.debug("Terminating service Entry for dpID {} : label : {} egress : {} installed successfully {}",
266 dpId, label, groupId);
269 public void createTerminatingServiceActions( BigInteger destDpId, int label, List<ActionInfo> actionsInfos) {
270 List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
272 LOG.info("create terminatingServiceAction on DpnId = {} and serviceId = {} and actions = {}", destDpId , label,actionsInfos);
275 mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {
276 MetaDataUtil.getTunnelIdWithValidVniBitAndVniSet(label),
277 MetaDataUtil.METADA_MASK_TUNNEL_ID }));
279 List<InstructionInfo> mkInstructions = new ArrayList<InstructionInfo>();
280 mkInstructions.add(new InstructionInfo(InstructionType.write_actions, actionsInfos));
282 FlowEntity terminatingServiceTableFlowEntity = MDSALUtil.buildFlowEntity(destDpId, INTERNAL_TUNNEL_TABLE,
283 getFlowRef(destDpId, INTERNAL_TUNNEL_TABLE,label), 5, String.format("%s:%d","TST Flow Entry ",label),
284 0, 0, COOKIE_TUNNEL.add(BigInteger.valueOf(label)),mkMatches, mkInstructions);
286 mdsalManager.installFlow(terminatingServiceTableFlowEntity);
289 private void removeTunnelTableEntry(BigInteger dpId, long label) {
290 FlowEntity flowEntity;
291 LOG.info("remove terminatingServiceActions called with DpnId = {} and label = {}", dpId , label);
292 List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
294 mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {
295 MetaDataUtil.getTunnelIdWithValidVniBitAndVniSet((int)label),
296 MetaDataUtil.METADA_MASK_TUNNEL_ID }));
297 flowEntity = MDSALUtil.buildFlowEntity(dpId,
298 INTERNAL_TUNNEL_TABLE,
299 getFlowRef(dpId, INTERNAL_TUNNEL_TABLE, (int)label),
300 5, String.format("%s:%d","TST Flow Entry ",label), 0, 0,
301 COOKIE_TUNNEL.add(BigInteger.valueOf(label)), mkMatches, null);
302 mdsalManager.removeFlow(flowEntity);
303 LOG.debug("Terminating service Entry for dpID {} : label : {} removed successfully {}",dpId, label);
306 public BigInteger deleteLocalFibEntry(Long vpnId, String rd, VrfEntry vrfEntry) {
307 BigInteger localDpnId = BigInteger.ZERO;
308 VpnNexthop localNextHopInfo = nextHopManager.getVpnNexthop(vpnId, vrfEntry.getDestPrefix());
309 boolean staticRoute = false;
311 //If the vrf entry is a static/extra route, the nexthop of the entry would be a adjacency in the vpn
312 if(localNextHopInfo == null) {
313 localNextHopInfo = nextHopManager.getVpnNexthop(vpnId, vrfEntry.getNextHopAddress() + "/32");
317 if(localNextHopInfo != null) {
318 localDpnId = localNextHopInfo.getDpnId();
319 if (getPrefixToInterface(vpnId, (staticRoute == true) ? vrfEntry.getNextHopAddress() + "/32" : vrfEntry.getDestPrefix()) == null) {
320 makeConnectedRoute(localDpnId, vpnId, vrfEntry, rd, null /* invalid */,
321 NwConstants.DEL_FLOW);
322 makeLFibTableEntry(localDpnId, vrfEntry.getLabel(), 0 /* invalid */,
323 vrfEntry.getNextHopAddress(), NwConstants.DEL_FLOW);
324 removeTunnelTableEntry(localDpnId, vrfEntry.getLabel());
325 deleteLocalAdjacency(localDpnId, vpnId, (staticRoute == true) ? vrfEntry.getNextHopAddress() + "/32" : vrfEntry.getDestPrefix());
331 private InstanceIdentifier<Prefixes> getPrefixToInterfaceIdentifier(Long vpnId, String ipPrefix) {
332 return InstanceIdentifier.builder(PrefixToInterface.class)
333 .child(VpnIds.class, new VpnIdsKey(vpnId)).child(Prefixes.class, new PrefixesKey(ipPrefix)).build();
336 private Prefixes getPrefixToInterface(Long vpnId, String ipPrefix) {
337 Optional<Prefixes> localNextHopInfoData =
338 read(LogicalDatastoreType.OPERATIONAL, getPrefixToInterfaceIdentifier(vpnId, ipPrefix));
339 return localNextHopInfoData.isPresent() ? localNextHopInfoData.get() : null;
343 private Class<? extends TunnelTypeBase> getTunnelType(String ifName) {
345 Future<RpcResult<GetTunnelTypeOutput>> result = interfaceManager.getTunnelType(
346 new GetTunnelTypeInputBuilder().setIntfName(ifName).build());
347 RpcResult<GetTunnelTypeOutput> rpcResult = result.get();
348 if(!rpcResult.isSuccessful()) {
349 LOG.warn("RPC Call to getTunnelInterfaceId returned with Errors {}", rpcResult.getErrors());
351 return rpcResult.getResult().getTunnelType();
354 } catch (InterruptedException | ExecutionException e) {
355 LOG.warn("Exception when getting tunnel interface Id for tunnel type {}", e);
361 private void createRemoteFibEntry(final BigInteger localDpnId, final BigInteger remoteDpnId,
362 final long vpnId, final VrfTablesKey vrfTableKey,
363 final VrfEntry vrfEntry) {
364 String rd = vrfTableKey.getRouteDistinguisher();
365 LOG.debug("adding route " + vrfEntry.getDestPrefix() + " " + rd);
366 /********************************************/
367 String tunnelInterface = resolveAdjacency(localDpnId, remoteDpnId, vpnId, vrfEntry);
368 if(tunnelInterface == null) {
369 LOG.error("Could not get interface for nexthop: {} in vpn {}",
370 vrfEntry.getNextHopAddress(), rd);
371 LOG.warn("Failed to add Route: {} in vpn: {}",
372 vrfEntry.getDestPrefix(), rd);
375 List<ActionInfo> actionInfos = nextHopManager.getEgressActionsForInterface(tunnelInterface);
376 Class<? extends TunnelTypeBase> tunnel_type = getTunnelType(tunnelInterface);
377 if (tunnel_type.equals(TunnelTypeMplsOverGre.class)) {
378 LOG.debug("Push label action for prefix {}", vrfEntry.getDestPrefix());
379 actionInfos.add(new ActionInfo(ActionType.push_mpls, new String[] { null }));
380 actionInfos.add(new ActionInfo(ActionType.set_field_mpls_label, new String[] { Long.toString(vrfEntry.getLabel())}));
382 int label = vrfEntry.getLabel().intValue();
384 if(tunnel_type.equals(TunnelTypeVxlan.class)) {
385 tunnelId = MetaDataUtil.getTunnelIdWithValidVniBitAndVniSet(label);
387 tunnelId = BigInteger.valueOf(label);
389 LOG.debug("adding set tunnel id action for label {}", label);
390 actionInfos.add(new ActionInfo(ActionType.set_field_tunnel_id, new BigInteger[] {
394 List<ActionInfo> actionInfos = resolveAdjacency(localDpnId, remoteDpnId, vpnId, vrfEntry);
395 if(actionInfos == null) {
396 LOG.error("Could not get nexthop group id for nexthop: {} in vpn {}",
397 vrfEntry.getNextHopAddress(), rd);
398 LOG.warn("Failed to add Route: {} in vpn: {}",
399 vrfEntry.getDestPrefix(), rd);
402 BigInteger dpnId = nextHopManager.getDpnForPrefix(vpnId, vrfEntry.getDestPrefix());
404 //This route may be extra route... try to query with nexthop Ip
405 LOG.debug("Checking for extra route to install remote fib entry {}", vrfEntry.getDestPrefix());
406 dpnId = nextHopManager.getDpnForPrefix(vpnId, vrfEntry.getNextHopAddress() + "/32");
409 LOG.debug("Push label action for prefix {}", vrfEntry.getDestPrefix());
410 actionInfos.add(new ActionInfo(ActionType.push_mpls, new String[] { null }));
411 actionInfos.add(new ActionInfo(ActionType.set_field_mpls_label, new String[] { Long.toString(vrfEntry.getLabel())}));
413 int label = vrfEntry.getLabel().intValue();
414 LOG.debug("adding set tunnel id action for label {}", label);
415 actionInfos.add(new ActionInfo(ActionType.set_field_tunnel_id, new BigInteger[] {
416 MetaDataUtil.getTunnelIdWithValidVniBitAndVniSet(label),
417 MetaDataUtil.METADA_MASK_VALID_TUNNEL_ID_BIT_AND_TUNNEL_ID }));
420 makeConnectedRoute(remoteDpnId, vpnId, vrfEntry, rd, actionInfos, NwConstants.ADD_FLOW);
422 "Successfully added fib entry for " + vrfEntry.getDestPrefix() + " vpnId " + vpnId);
425 private void deleteFibEntries(final InstanceIdentifier<VrfEntry> identifier,
426 final VrfEntry vrfEntry) {
427 final VrfTablesKey vrfTableKey = identifier.firstKeyOf(VrfTables.class, VrfTablesKey.class);
428 Preconditions.checkNotNull(vrfTableKey, "VrfTablesKey cannot be null or empty!");
429 Preconditions.checkNotNull(vrfEntry, "VrfEntry cannot be null or empty!");
431 VpnInstanceOpDataEntry vpnInstance = getVpnInstance(vrfTableKey.getRouteDistinguisher());
432 Preconditions.checkNotNull(vpnInstance, "Vpn Instance not available!");
433 Collection<VpnToDpnList> vpnToDpnList = vpnInstance.getVpnToDpnList();
434 if (vpnToDpnList != null) {
435 BigInteger localDpnId = deleteLocalFibEntry(vpnInstance.getVpnId(),
436 vrfTableKey.getRouteDistinguisher(), vrfEntry);
437 for (VpnToDpnList curDpn : vpnToDpnList) {
438 if (!curDpn.getDpnId().equals(localDpnId)) {
439 deleteRemoteRoute(localDpnId, curDpn.getDpnId(), vpnInstance.getVpnId(), vrfTableKey, vrfEntry);
446 public void deleteRemoteRoute(final BigInteger localDpnId, final BigInteger remoteDpnId,
447 final long vpnId, final VrfTablesKey vrfTableKey,
448 final VrfEntry vrfEntry) {
449 LOG.debug("deleting route "+ vrfEntry.getDestPrefix() + " "+vpnId);
450 String rd = vrfTableKey.getRouteDistinguisher();
451 String egressInterface = resolveAdjacency(localDpnId, remoteDpnId, vpnId, vrfEntry);
452 if(egressInterface == null) {
453 LOG.error("Could not get nexthop group id for nexthop: {} in vpn {}",
454 vrfEntry.getNextHopAddress(), rd);
455 LOG.warn("Failed to delete Route: {} in vpn: {}",
456 vrfEntry.getDestPrefix(), rd);
460 makeConnectedRoute(remoteDpnId, vpnId, vrfEntry, rd, null, NwConstants.DEL_FLOW);
461 LOG.debug("Successfully delete fib entry for "+ vrfEntry.getDestPrefix() + " vpnId "+vpnId);
464 private long getIpAddress(byte[] rawIpAddress) {
465 return (((rawIpAddress[0] & 0xFF) << (3 * 8)) + ((rawIpAddress[1] & 0xFF) << (2 * 8))
466 + ((rawIpAddress[2] & 0xFF) << (1 * 8)) + (rawIpAddress[3] & 0xFF)) & 0xffffffffL;
469 private void makeConnectedRoute(BigInteger dpId, long vpnId, VrfEntry vrfEntry, String rd,
470 List<ActionInfo> actionInfos, int addOrRemove) {
471 LOG.trace("makeConnectedRoute: vrfEntry {}",vrfEntry);
472 String values[] = vrfEntry.getDestPrefix().split("/");
473 String ipAddress = values[0];
474 int prefixLength = (values.length == 1) ? 0 : Integer.parseInt(values[1]);
475 LOG.debug("Adding route to DPN. ip {} masklen {}", ipAddress, prefixLength);
476 InetAddress destPrefix = null;
478 destPrefix = InetAddress.getByName(ipAddress);
479 } catch (UnknownHostException e) {
480 LOG.error("UnknowHostException in addRoute. Failed to add Route for ipPrefix {}", vrfEntry.getDestPrefix());
484 List<MatchInfo> matches = new ArrayList<MatchInfo>();
486 matches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
487 BigInteger.valueOf(vpnId), MetaDataUtil.METADATA_MASK_VRFID }));
489 matches.add(new MatchInfo(MatchFieldType.eth_type,
490 new long[] { 0x0800L }));
492 if(prefixLength != 0) {
493 matches.add(new MatchInfo(MatchFieldType.ipv4_dst, new long[] {
494 getIpAddress(destPrefix.getAddress()), prefixLength }));
497 List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
498 if(addOrRemove == NwConstants.ADD_FLOW) {
499 instructions.add(new InstructionInfo(InstructionType.write_actions, actionInfos));
502 String flowRef = getFlowRef(dpId, L3_FIB_TABLE, rd, destPrefix);
504 FlowEntity flowEntity;
506 int priority = DEFAULT_FIB_FLOW_PRIORITY + prefixLength;
507 flowEntity = MDSALUtil.buildFlowEntity(dpId, L3_FIB_TABLE, flowRef,
508 priority, flowRef, 0, 0,
509 COOKIE_VM_FIB_TABLE, matches, instructions);
511 if (addOrRemove == NwConstants.ADD_FLOW) {
512 /* We need to call sync API to install flow so that 2 DS operations on the same object do not
513 * happen at same time. However, MDSALManager's syncInstallFlow takes a delay time (or uses a default one) to wait
514 * for or for notification that operational DS write for flows is done. We do not turn on the stats writing for flows,
515 * so that notification never comes, so we do not need that wait. Sending the lowest value of wait "1 ms" since 0 wait means
516 * wait indefinitely. */
517 // FIXME: sync calls.
518 //mdsalManager.syncInstallFlow(flowEntity, 1);
519 mdsalManager.installFlow(flowEntity);
521 // FIXME: sync calls.
522 // mdsalManager.syncRemoveFlow(flowEntity, 1);
523 mdsalManager.removeFlow(flowEntity);
527 private void makeLFibTableEntry(BigInteger dpId, long label, long groupId,
528 String nextHop, int addOrRemove) {
529 List<MatchInfo> matches = new ArrayList<MatchInfo>();
530 matches.add(new MatchInfo(MatchFieldType.eth_type,
531 new long[] { 0x8847L }));
532 matches.add(new MatchInfo(MatchFieldType.mpls_label, new String[]{Long.toString(label)}));
534 List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
535 List<ActionInfo> actionsInfos = new ArrayList<ActionInfo>();
536 actionsInfos.add(new ActionInfo(ActionType.pop_mpls, new String[]{}));
537 actionsInfos.add(new ActionInfo(ActionType.group, new String[] { String.valueOf(groupId) }));
538 instructions.add(new InstructionInfo(InstructionType.write_actions, actionsInfos));
540 // Install the flow entry in L3_LFIB_TABLE
541 String flowRef = getFlowRef(dpId, L3_LFIB_TABLE, label, nextHop);
543 FlowEntity flowEntity;
544 flowEntity = MDSALUtil.buildFlowEntity(dpId, L3_LFIB_TABLE, flowRef,
545 DEFAULT_FIB_FLOW_PRIORITY, flowRef, 0, 0,
546 COOKIE_VM_LFIB_TABLE, matches, instructions);
548 if (addOrRemove == NwConstants.ADD_FLOW) {
549 /* We need to call sync API to install flow so that 2 DS operations on the same object do not
550 * happen at same time. However, MDSALManager's syncInstallFlow takes a delay time (or uses a default one) to wait
551 * for or for notification that operational DS write for flows is done. We do not turn on the stats writing for flows,
552 * so that notification never comes, so we do not need that wait. Sending the lowest value of wait "1 ms" since 0 wait means
553 * wait indefinitely. */
556 // mdsalManager.syncInstallFlow(flowEntity, 1);
557 mdsalManager.installFlow(flowEntity);
560 // mdsalManager.syncRemoveFlow(flowEntity, 1);
561 mdsalManager.removeFlow(flowEntity);
563 LOG.debug("LFIB Entry for dpID {} : label : {} group {} modified successfully {}",dpId, label, groupId );
566 private void deleteLocalAdjacency(final BigInteger dpId, final long vpnId, final String ipAddress) {
567 LOG.trace("deleteLocalAdjacency called with dpid {}, vpnId{}, ipAddress {}",dpId, vpnId, ipAddress);
569 nextHopManager.removeLocalNextHop(dpId, vpnId, ipAddress);
570 } catch (NullPointerException e) {
575 public void populateFibOnNewDpn(BigInteger dpnId, long vpnId, String rd) {
576 LOG.trace("New dpn {} for vpn {} : populateFibOnNewDpn", dpnId, rd);
577 InstanceIdentifier<VrfTables> id = buildVrfId(rd);
578 Optional<VrfTables> vrfTable = read(LogicalDatastoreType.OPERATIONAL, id);
579 if(vrfTable.isPresent()) {
580 for(VrfEntry vrfEntry : vrfTable.get().getVrfEntry()) {
581 // Passing null as we don't know the dpn
582 // to which prefix is attached at this point
583 createRemoteFibEntry(null, dpnId, vpnId, vrfTable.get().getKey(), vrfEntry);
588 public void cleanUpDpnForVpn(BigInteger dpnId, long vpnId, String rd) {
589 LOG.trace("Remove dpn {} for vpn {} : cleanUpDpnForVpn", dpnId, rd);
590 InstanceIdentifier<VrfTables> id = buildVrfId(rd);
591 Optional<VrfTables> vrfTable = read(LogicalDatastoreType.OPERATIONAL, id);
592 if(vrfTable.isPresent()) {
593 for(VrfEntry vrfEntry : vrfTable.get().getVrfEntry()) {
594 // Passing null as we don't know the dpn
595 // to which prefix is attached at this point
596 deleteRemoteRoute(null, dpnId, vpnId, vrfTable.get().getKey(), vrfEntry);
601 public static InstanceIdentifier<VrfTables> buildVrfId(String rd) {
602 InstanceIdentifierBuilder<VrfTables> idBuilder =
603 InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(rd));
604 InstanceIdentifier<VrfTables> id = idBuilder.build();
608 private String getFlowRef(BigInteger dpnId, short tableId, long label, String nextHop) {
609 return new StringBuilder(64).append(FLOWID_PREFIX).append(dpnId).append(NwConstants.FLOWID_SEPARATOR)
610 .append(tableId).append(NwConstants.FLOWID_SEPARATOR)
611 .append(label).append(NwConstants.FLOWID_SEPARATOR)
612 .append(nextHop).toString();
615 private String getFlowRef(BigInteger dpnId, short tableId, String rd, InetAddress destPrefix) {
616 return new StringBuilder(64).append(FLOWID_PREFIX).append(dpnId).append(NwConstants.FLOWID_SEPARATOR)
617 .append(tableId).append(NwConstants.FLOWID_SEPARATOR)
618 .append(rd).append(NwConstants.FLOWID_SEPARATOR)
619 .append(destPrefix.getHostAddress()).toString();
622 protected String resolveAdjacency(final BigInteger localDpnId, final BigInteger remoteDpnId,
623 final long vpnId, final VrfEntry vrfEntry) {
624 String adjacency = null;
625 LOG.trace("resolveAdjacency called with localdpid{} remotedpid {}, vpnId{}, VrfEntry {}", localDpnId, remoteDpnId, vpnId, vrfEntry);;
628 nextHopManager.getRemoteNextHopPointer(localDpnId, remoteDpnId, vpnId,
629 vrfEntry.getDestPrefix(),
630 vrfEntry.getNextHopAddress());
631 } catch (NullPointerException e) {
637 protected VpnInstanceOpDataEntry getVpnInstance(String rd) {
638 InstanceIdentifier<VpnInstanceOpDataEntry> id = InstanceIdentifier.create(VpnInstanceOpData.class).child(
639 VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(rd));
640 Optional<VpnInstanceOpDataEntry> vpnInstanceOpData = read(LogicalDatastoreType.OPERATIONAL, id);
641 if(vpnInstanceOpData.isPresent()) {
642 return vpnInstanceOpData.get();
647 public void processNodeAdd(BigInteger dpnId) {
648 LOG.debug("Received notification to install TableMiss entries for dpn {} ", dpnId);
649 makeTableMissFlow(dpnId, NwConstants.ADD_FLOW);
650 makeProtocolTableFlow(dpnId, NwConstants.ADD_FLOW);
651 makeL3IntfTblMissFlow(dpnId, NwConstants.ADD_FLOW);
654 private void makeTableMissFlow(BigInteger dpnId, int addOrRemove) {
655 final BigInteger COOKIE_TABLE_MISS = new BigInteger("1030000", 16);
656 // Instruction to goto L3 InterfaceTable
657 List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
658 instructions.add(new InstructionInfo(InstructionType.goto_table, new long[] { L3_INTERFACE_TABLE }));
659 List<MatchInfo> matches = new ArrayList<MatchInfo>();
660 FlowEntity flowEntityLfib = MDSALUtil.buildFlowEntity(dpnId, L3_LFIB_TABLE,
661 getFlowRef(dpnId, L3_LFIB_TABLE, NwConstants.TABLE_MISS_FLOW),
662 NwConstants.TABLE_MISS_PRIORITY, "Table Miss", 0, 0, COOKIE_TABLE_MISS, matches, instructions);
664 FlowEntity flowEntityFib = MDSALUtil.buildFlowEntity(dpnId,L3_FIB_TABLE, getFlowRef(dpnId, L3_FIB_TABLE, NwConstants.TABLE_MISS_FLOW),
665 NwConstants.TABLE_MISS_PRIORITY, "FIB Table Miss Flow", 0, 0, COOKIE_VM_FIB_TABLE,
666 matches, instructions);
668 if (addOrRemove == NwConstants.ADD_FLOW) {
669 LOG.debug("Invoking MDSAL to install Table Miss Entries");
670 mdsalManager.installFlow(flowEntityLfib);
671 mdsalManager.installFlow(flowEntityFib);
673 mdsalManager.removeFlow(flowEntityLfib);
674 mdsalManager.removeFlow(flowEntityFib);
679 private String getFlowRef(BigInteger dpnId, short tableId, int tableMiss) {
680 return new StringBuffer().append(FLOWID_PREFIX).append(dpnId).append(NwConstants.FLOWID_SEPARATOR)
681 .append(tableId).append(NwConstants.FLOWID_SEPARATOR).append(tableMiss)
682 .append(FLOWID_PREFIX).toString();
686 * Install flow entry in protocol table to forward mpls
687 * coming through gre tunnel to LFIB table.
689 private void makeProtocolTableFlow(BigInteger dpnId, int addOrRemove) {
690 final BigInteger COOKIE_PROTOCOL_TABLE = new BigInteger("1070000", 16);
691 // Instruction to goto L3 InterfaceTable
692 List<InstructionInfo> instructions = new ArrayList<>();
693 instructions.add(new InstructionInfo(InstructionType.goto_table, new long[] {L3_LFIB_TABLE}));
694 List<MatchInfo> matches = new ArrayList<MatchInfo>();
695 matches.add(new MatchInfo(MatchFieldType.eth_type,
696 new long[] { 0x8847L }));
697 FlowEntity flowEntityToLfib = MDSALUtil.buildFlowEntity(dpnId, L3_PROTOCOL_TABLE,
698 getFlowRef(dpnId, L3_PROTOCOL_TABLE,
700 DEFAULT_FIB_FLOW_PRIORITY,
701 "Protocol Table For LFIB",
703 COOKIE_PROTOCOL_TABLE,
704 matches, instructions);
706 if (addOrRemove == NwConstants.ADD_FLOW) {
707 LOG.debug("Invoking MDSAL to install Protocol Entries for dpn {}", dpnId);
708 mdsalManager.installFlow(flowEntityToLfib);
710 mdsalManager.removeFlow(flowEntityToLfib);
714 public List<String> printFibEntries() {
715 List<String> result = new ArrayList<String>();
716 result.add(String.format(" %-7s %-20s %-20s %-7s", "RD", "Prefix", "Nexthop", "Label"));
717 result.add("-------------------------------------------------------------------");
718 InstanceIdentifier<FibEntries> id = InstanceIdentifier.create(FibEntries.class);
719 Optional<FibEntries> fibEntries = read(LogicalDatastoreType.OPERATIONAL, id);
720 if (fibEntries.isPresent()) {
721 List<VrfTables> vrfTables = fibEntries.get().getVrfTables();
722 for (VrfTables vrfTable : vrfTables) {
723 for (VrfEntry vrfEntry : vrfTable.getVrfEntry()) {
724 result.add(String.format(" %-7s %-20s %-20s %-7s", vrfTable.getRouteDistinguisher(),
725 vrfEntry.getDestPrefix(), vrfEntry.getNextHopAddress(), vrfEntry.getLabel()));
732 private void makeL3IntfTblMissFlow(BigInteger dpnId, int addOrRemove) {
733 List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
734 List<MatchInfo> matches = new ArrayList<MatchInfo>();
735 final BigInteger COOKIE_TABLE_MISS = new BigInteger("1030000", 16);
736 // Instruction to clear metadata except SI and LportTag bits
737 instructions.add(new InstructionInfo(InstructionType.write_metadata, new BigInteger[] {
738 CLEAR_METADATA, METADATA_MASK_CLEAR }));
739 // Instruction to clear action
740 instructions.add(new InstructionInfo(InstructionType.clear_actions));
741 // Instruction to goto L3 InterfaceTable
743 instructions.add(new InstructionInfo(InstructionType.goto_table, new long[] { LPORT_DISPATCHER_TABLE }));
745 FlowEntity flowEntityL3Intf = MDSALUtil.buildFlowEntity(dpnId, L3_INTERFACE_TABLE,
746 getFlowRef(dpnId, L3_INTERFACE_TABLE, NwConstants.TABLE_MISS_FLOW),
747 NwConstants.TABLE_MISS_PRIORITY, "L3 Interface Table Miss", 0, 0, COOKIE_TABLE_MISS, matches, instructions);
748 if (addOrRemove == NwConstants.ADD_FLOW) {
749 LOG.info("Invoking MDSAL to install L3 interface Table Miss Entries");
750 mdsalManager.installFlow(flowEntityL3Intf);
752 mdsalManager.removeFlow(flowEntityL3Intf);