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 BigInteger localDpnId = createLocalFibEntry(vpnInstance.getVpnId(),
217 vrfTableKey.getRouteDistinguisher(), vrfEntry);
218 if (vpnToDpnList != null) {
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 // FIXME vxlan vni bit set is not working properly with OVS.need to revisit
276 mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {BigInteger.valueOf(label)}));
278 List<InstructionInfo> mkInstructions = new ArrayList<InstructionInfo>();
279 mkInstructions.add(new InstructionInfo(InstructionType.write_actions, actionsInfos));
281 FlowEntity terminatingServiceTableFlowEntity = MDSALUtil.buildFlowEntity(destDpId, INTERNAL_TUNNEL_TABLE,
282 getFlowRef(destDpId, INTERNAL_TUNNEL_TABLE,label), 5, String.format("%s:%d","TST Flow Entry ",label),
283 0, 0, COOKIE_TUNNEL.add(BigInteger.valueOf(label)),mkMatches, mkInstructions);
285 mdsalManager.installFlow(terminatingServiceTableFlowEntity);
288 private void removeTunnelTableEntry(BigInteger dpId, long label) {
289 FlowEntity flowEntity;
290 LOG.info("remove terminatingServiceActions called with DpnId = {} and label = {}", dpId , label);
291 List<MatchInfo> mkMatches = new ArrayList<MatchInfo>();
293 mkMatches.add(new MatchInfo(MatchFieldType.tunnel_id, new BigInteger[] {
294 MetaDataUtil.getTunnelIdWithValidVniBitAndVniSet((int)label),
295 MetaDataUtil.METADA_MASK_TUNNEL_ID }));
296 flowEntity = MDSALUtil.buildFlowEntity(dpId,
297 INTERNAL_TUNNEL_TABLE,
298 getFlowRef(dpId, INTERNAL_TUNNEL_TABLE, (int)label),
299 5, String.format("%s:%d","TST Flow Entry ",label), 0, 0,
300 COOKIE_TUNNEL.add(BigInteger.valueOf(label)), mkMatches, null);
301 mdsalManager.removeFlow(flowEntity);
302 LOG.debug("Terminating service Entry for dpID {} : label : {} removed successfully {}",dpId, label);
305 public BigInteger deleteLocalFibEntry(Long vpnId, String rd, VrfEntry vrfEntry) {
306 BigInteger localDpnId = BigInteger.ZERO;
307 VpnNexthop localNextHopInfo = nextHopManager.getVpnNexthop(vpnId, vrfEntry.getDestPrefix());
308 boolean staticRoute = false;
310 //If the vrf entry is a static/extra route, the nexthop of the entry would be a adjacency in the vpn
311 if(localNextHopInfo == null) {
312 localNextHopInfo = nextHopManager.getVpnNexthop(vpnId, vrfEntry.getNextHopAddress() + "/32");
316 if(localNextHopInfo != null) {
317 localDpnId = localNextHopInfo.getDpnId();
318 if (getPrefixToInterface(vpnId, (staticRoute == true) ? vrfEntry.getNextHopAddress() + "/32" : vrfEntry.getDestPrefix()) == null) {
319 makeConnectedRoute(localDpnId, vpnId, vrfEntry, rd, null /* invalid */,
320 NwConstants.DEL_FLOW);
321 makeLFibTableEntry(localDpnId, vrfEntry.getLabel(), 0 /* invalid */,
322 vrfEntry.getNextHopAddress(), NwConstants.DEL_FLOW);
323 removeTunnelTableEntry(localDpnId, vrfEntry.getLabel());
324 deleteLocalAdjacency(localDpnId, vpnId, (staticRoute == true) ? vrfEntry.getNextHopAddress() + "/32" : vrfEntry.getDestPrefix());
330 private InstanceIdentifier<Prefixes> getPrefixToInterfaceIdentifier(Long vpnId, String ipPrefix) {
331 return InstanceIdentifier.builder(PrefixToInterface.class)
332 .child(VpnIds.class, new VpnIdsKey(vpnId)).child(Prefixes.class, new PrefixesKey(ipPrefix)).build();
335 private Prefixes getPrefixToInterface(Long vpnId, String ipPrefix) {
336 Optional<Prefixes> localNextHopInfoData =
337 read(LogicalDatastoreType.OPERATIONAL, getPrefixToInterfaceIdentifier(vpnId, ipPrefix));
338 return localNextHopInfoData.isPresent() ? localNextHopInfoData.get() : null;
342 private Class<? extends TunnelTypeBase> getTunnelType(String ifName) {
344 Future<RpcResult<GetTunnelTypeOutput>> result = interfaceManager.getTunnelType(
345 new GetTunnelTypeInputBuilder().setIntfName(ifName).build());
346 RpcResult<GetTunnelTypeOutput> rpcResult = result.get();
347 if(!rpcResult.isSuccessful()) {
348 LOG.warn("RPC Call to getTunnelInterfaceId returned with Errors {}", rpcResult.getErrors());
350 return rpcResult.getResult().getTunnelType();
353 } catch (InterruptedException | ExecutionException e) {
354 LOG.warn("Exception when getting tunnel interface Id for tunnel type {}", e);
360 private void createRemoteFibEntry(final BigInteger localDpnId, final BigInteger remoteDpnId,
361 final long vpnId, final VrfTablesKey vrfTableKey,
362 final VrfEntry vrfEntry) {
363 String rd = vrfTableKey.getRouteDistinguisher();
364 LOG.debug("adding route " + vrfEntry.getDestPrefix() + " " + rd);
365 /********************************************/
366 String tunnelInterface = resolveAdjacency(localDpnId, remoteDpnId, vpnId, vrfEntry);
367 if(tunnelInterface == null) {
368 LOG.error("Could not get interface for nexthop: {} in vpn {}",
369 vrfEntry.getNextHopAddress(), rd);
370 LOG.warn("Failed to add Route: {} in vpn: {}",
371 vrfEntry.getDestPrefix(), rd);
374 List<ActionInfo> actionInfos = new ArrayList<>();
375 Class<? extends TunnelTypeBase> tunnel_type = getTunnelType(tunnelInterface);
376 if (tunnel_type.equals(TunnelTypeMplsOverGre.class)) {
377 LOG.debug("Push label action for prefix {}", vrfEntry.getDestPrefix());
378 actionInfos.add(new ActionInfo(ActionType.push_mpls, new String[] { null }));
379 actionInfos.add(new ActionInfo(ActionType.set_field_mpls_label, new String[] { Long.toString(vrfEntry.getLabel())}));
381 int label = vrfEntry.getLabel().intValue();
383 // FIXME vxlan vni bit set is not working properly with OVS.need to revisit
384 if(tunnel_type.equals(TunnelTypeVxlan.class)) {
385 tunnelId = BigInteger.valueOf(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[]{
393 actionInfos.addAll(nextHopManager.getEgressActionsForInterface(tunnelInterface));
395 List<ActionInfo> actionInfos = resolveAdjacency(localDpnId, remoteDpnId, vpnId, vrfEntry);
396 if(actionInfos == null) {
397 LOG.error("Could not get nexthop group id for nexthop: {} in vpn {}",
398 vrfEntry.getNextHopAddress(), rd);
399 LOG.warn("Failed to add Route: {} in vpn: {}",
400 vrfEntry.getDestPrefix(), rd);
403 BigInteger dpnId = nextHopManager.getDpnForPrefix(vpnId, vrfEntry.getDestPrefix());
405 //This route may be extra route... try to query with nexthop Ip
406 LOG.debug("Checking for extra route to install remote fib entry {}", vrfEntry.getDestPrefix());
407 dpnId = nextHopManager.getDpnForPrefix(vpnId, vrfEntry.getNextHopAddress() + "/32");
410 LOG.debug("Push label action for prefix {}", vrfEntry.getDestPrefix());
411 actionInfos.add(new ActionInfo(ActionType.push_mpls, new String[] { null }));
412 actionInfos.add(new ActionInfo(ActionType.set_field_mpls_label, new String[] { Long.toString(vrfEntry.getLabel())}));
414 int label = vrfEntry.getLabel().intValue();
415 LOG.debug("adding set tunnel id action for label {}", label);
416 actionInfos.add(new ActionInfo(ActionType.set_field_tunnel_id, new BigInteger[] {
417 MetaDataUtil.getTunnelIdWithValidVniBitAndVniSet(label),
418 MetaDataUtil.METADA_MASK_VALID_TUNNEL_ID_BIT_AND_TUNNEL_ID }));
421 makeConnectedRoute(remoteDpnId, vpnId, vrfEntry, rd, actionInfos, NwConstants.ADD_FLOW);
423 "Successfully added fib entry for " + vrfEntry.getDestPrefix() + " vpnId " + vpnId);
426 private void deleteFibEntries(final InstanceIdentifier<VrfEntry> identifier,
427 final VrfEntry vrfEntry) {
428 final VrfTablesKey vrfTableKey = identifier.firstKeyOf(VrfTables.class, VrfTablesKey.class);
429 Preconditions.checkNotNull(vrfTableKey, "VrfTablesKey cannot be null or empty!");
430 Preconditions.checkNotNull(vrfEntry, "VrfEntry cannot be null or empty!");
432 VpnInstanceOpDataEntry vpnInstance = getVpnInstance(vrfTableKey.getRouteDistinguisher());
433 Preconditions.checkNotNull(vpnInstance, "Vpn Instance not available!");
434 Collection<VpnToDpnList> vpnToDpnList = vpnInstance.getVpnToDpnList();
435 BigInteger localDpnId = deleteLocalFibEntry(vpnInstance.getVpnId(),
436 vrfTableKey.getRouteDistinguisher(), vrfEntry);
437 if (vpnToDpnList != null) {
438 for (VpnToDpnList curDpn : vpnToDpnList) {
439 if (!curDpn.getDpnId().equals(localDpnId)) {
440 deleteRemoteRoute(localDpnId, curDpn.getDpnId(), vpnInstance.getVpnId(), vrfTableKey, vrfEntry);
447 public void deleteRemoteRoute(final BigInteger localDpnId, final BigInteger remoteDpnId,
448 final long vpnId, final VrfTablesKey vrfTableKey,
449 final VrfEntry vrfEntry) {
450 LOG.debug("deleting route "+ vrfEntry.getDestPrefix() + " "+vpnId);
451 String rd = vrfTableKey.getRouteDistinguisher();
452 String egressInterface = resolveAdjacency(localDpnId, remoteDpnId, vpnId, vrfEntry);
453 if(egressInterface == null) {
454 LOG.error("Could not get nexthop group id for nexthop: {} in vpn {}",
455 vrfEntry.getNextHopAddress(), rd);
456 LOG.warn("Failed to delete Route: {} in vpn: {}",
457 vrfEntry.getDestPrefix(), rd);
461 makeConnectedRoute(remoteDpnId, vpnId, vrfEntry, rd, null, NwConstants.DEL_FLOW);
462 LOG.debug("Successfully delete fib entry for "+ vrfEntry.getDestPrefix() + " vpnId "+vpnId);
465 private long getIpAddress(byte[] rawIpAddress) {
466 return (((rawIpAddress[0] & 0xFF) << (3 * 8)) + ((rawIpAddress[1] & 0xFF) << (2 * 8))
467 + ((rawIpAddress[2] & 0xFF) << (1 * 8)) + (rawIpAddress[3] & 0xFF)) & 0xffffffffL;
470 private void makeConnectedRoute(BigInteger dpId, long vpnId, VrfEntry vrfEntry, String rd,
471 List<ActionInfo> actionInfos, int addOrRemove) {
472 LOG.trace("makeConnectedRoute: vrfEntry {}",vrfEntry);
473 String values[] = vrfEntry.getDestPrefix().split("/");
474 String ipAddress = values[0];
475 int prefixLength = (values.length == 1) ? 0 : Integer.parseInt(values[1]);
476 LOG.debug("Adding route to DPN. ip {} masklen {}", ipAddress, prefixLength);
477 InetAddress destPrefix = null;
479 destPrefix = InetAddress.getByName(ipAddress);
480 } catch (UnknownHostException e) {
481 LOG.error("UnknowHostException in addRoute. Failed to add Route for ipPrefix {}", vrfEntry.getDestPrefix());
485 List<MatchInfo> matches = new ArrayList<MatchInfo>();
487 matches.add(new MatchInfo(MatchFieldType.metadata, new BigInteger[] {
488 BigInteger.valueOf(vpnId), MetaDataUtil.METADATA_MASK_VRFID }));
490 matches.add(new MatchInfo(MatchFieldType.eth_type,
491 new long[] { 0x0800L }));
493 if(prefixLength != 0) {
494 matches.add(new MatchInfo(MatchFieldType.ipv4_dst, new long[] {
495 getIpAddress(destPrefix.getAddress()), prefixLength }));
498 List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
499 if(addOrRemove == NwConstants.ADD_FLOW) {
500 instructions.add(new InstructionInfo(InstructionType.write_actions, actionInfos));
503 String flowRef = getFlowRef(dpId, L3_FIB_TABLE, rd, destPrefix);
505 FlowEntity flowEntity;
507 int priority = DEFAULT_FIB_FLOW_PRIORITY + prefixLength;
508 flowEntity = MDSALUtil.buildFlowEntity(dpId, L3_FIB_TABLE, flowRef,
509 priority, flowRef, 0, 0,
510 COOKIE_VM_FIB_TABLE, matches, instructions);
512 if (addOrRemove == NwConstants.ADD_FLOW) {
513 /* We need to call sync API to install flow so that 2 DS operations on the same object do not
514 * happen at same time. However, MDSALManager's syncInstallFlow takes a delay time (or uses a default one) to wait
515 * for or for notification that operational DS write for flows is done. We do not turn on the stats writing for flows,
516 * so that notification never comes, so we do not need that wait. Sending the lowest value of wait "1 ms" since 0 wait means
517 * wait indefinitely. */
518 // FIXME: sync calls.
519 //mdsalManager.syncInstallFlow(flowEntity, 1);
520 mdsalManager.installFlow(flowEntity);
522 // FIXME: sync calls.
523 // mdsalManager.syncRemoveFlow(flowEntity, 1);
524 mdsalManager.removeFlow(flowEntity);
528 private void makeLFibTableEntry(BigInteger dpId, long label, long groupId,
529 String nextHop, int addOrRemove) {
530 List<MatchInfo> matches = new ArrayList<MatchInfo>();
531 matches.add(new MatchInfo(MatchFieldType.eth_type,
532 new long[] { 0x8847L }));
533 matches.add(new MatchInfo(MatchFieldType.mpls_label, new String[]{Long.toString(label)}));
535 List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
536 List<ActionInfo> actionsInfos = new ArrayList<ActionInfo>();
537 actionsInfos.add(new ActionInfo(ActionType.pop_mpls, new String[]{}));
538 actionsInfos.add(new ActionInfo(ActionType.group, new String[] { String.valueOf(groupId) }));
539 instructions.add(new InstructionInfo(InstructionType.write_actions, actionsInfos));
541 // Install the flow entry in L3_LFIB_TABLE
542 String flowRef = getFlowRef(dpId, L3_LFIB_TABLE, label, nextHop);
544 FlowEntity flowEntity;
545 flowEntity = MDSALUtil.buildFlowEntity(dpId, L3_LFIB_TABLE, flowRef,
546 DEFAULT_FIB_FLOW_PRIORITY, flowRef, 0, 0,
547 COOKIE_VM_LFIB_TABLE, matches, instructions);
549 if (addOrRemove == NwConstants.ADD_FLOW) {
550 /* We need to call sync API to install flow so that 2 DS operations on the same object do not
551 * happen at same time. However, MDSALManager's syncInstallFlow takes a delay time (or uses a default one) to wait
552 * for or for notification that operational DS write for flows is done. We do not turn on the stats writing for flows,
553 * so that notification never comes, so we do not need that wait. Sending the lowest value of wait "1 ms" since 0 wait means
554 * wait indefinitely. */
557 // mdsalManager.syncInstallFlow(flowEntity, 1);
558 mdsalManager.installFlow(flowEntity);
561 // mdsalManager.syncRemoveFlow(flowEntity, 1);
562 mdsalManager.removeFlow(flowEntity);
564 LOG.debug("LFIB Entry for dpID {} : label : {} group {} modified successfully {}",dpId, label, groupId );
567 private void deleteLocalAdjacency(final BigInteger dpId, final long vpnId, final String ipAddress) {
568 LOG.trace("deleteLocalAdjacency called with dpid {}, vpnId{}, ipAddress {}",dpId, vpnId, ipAddress);
570 nextHopManager.removeLocalNextHop(dpId, vpnId, ipAddress);
571 } catch (NullPointerException e) {
576 public void populateFibOnNewDpn(BigInteger dpnId, long vpnId, String rd) {
577 LOG.trace("New dpn {} for vpn {} : populateFibOnNewDpn", dpnId, rd);
578 InstanceIdentifier<VrfTables> id = buildVrfId(rd);
579 Optional<VrfTables> vrfTable = read(LogicalDatastoreType.OPERATIONAL, id);
580 if(vrfTable.isPresent()) {
581 for(VrfEntry vrfEntry : vrfTable.get().getVrfEntry()) {
582 // Passing null as we don't know the dpn
583 // to which prefix is attached at this point
584 createRemoteFibEntry(null, dpnId, vpnId, vrfTable.get().getKey(), vrfEntry);
589 public void cleanUpDpnForVpn(BigInteger dpnId, long vpnId, String rd) {
590 LOG.trace("Remove dpn {} for vpn {} : cleanUpDpnForVpn", dpnId, rd);
591 InstanceIdentifier<VrfTables> id = buildVrfId(rd);
592 Optional<VrfTables> vrfTable = read(LogicalDatastoreType.OPERATIONAL, id);
593 if(vrfTable.isPresent()) {
594 for(VrfEntry vrfEntry : vrfTable.get().getVrfEntry()) {
595 // Passing null as we don't know the dpn
596 // to which prefix is attached at this point
597 deleteRemoteRoute(null, dpnId, vpnId, vrfTable.get().getKey(), vrfEntry);
602 public static InstanceIdentifier<VrfTables> buildVrfId(String rd) {
603 InstanceIdentifierBuilder<VrfTables> idBuilder =
604 InstanceIdentifier.builder(FibEntries.class).child(VrfTables.class, new VrfTablesKey(rd));
605 InstanceIdentifier<VrfTables> id = idBuilder.build();
609 private String getFlowRef(BigInteger dpnId, short tableId, long label, String nextHop) {
610 return new StringBuilder(64).append(FLOWID_PREFIX).append(dpnId).append(NwConstants.FLOWID_SEPARATOR)
611 .append(tableId).append(NwConstants.FLOWID_SEPARATOR)
612 .append(label).append(NwConstants.FLOWID_SEPARATOR)
613 .append(nextHop).toString();
616 private String getFlowRef(BigInteger dpnId, short tableId, String rd, InetAddress destPrefix) {
617 return new StringBuilder(64).append(FLOWID_PREFIX).append(dpnId).append(NwConstants.FLOWID_SEPARATOR)
618 .append(tableId).append(NwConstants.FLOWID_SEPARATOR)
619 .append(rd).append(NwConstants.FLOWID_SEPARATOR)
620 .append(destPrefix.getHostAddress()).toString();
623 protected String resolveAdjacency(final BigInteger localDpnId, final BigInteger remoteDpnId,
624 final long vpnId, final VrfEntry vrfEntry) {
625 String adjacency = null;
626 LOG.trace("resolveAdjacency called with localdpid{} remotedpid {}, vpnId{}, VrfEntry {}", localDpnId, remoteDpnId, vpnId, vrfEntry);;
629 nextHopManager.getRemoteNextHopPointer(localDpnId, remoteDpnId, vpnId,
630 vrfEntry.getDestPrefix(),
631 vrfEntry.getNextHopAddress());
632 } catch (NullPointerException e) {
638 protected VpnInstanceOpDataEntry getVpnInstance(String rd) {
639 InstanceIdentifier<VpnInstanceOpDataEntry> id = InstanceIdentifier.create(VpnInstanceOpData.class).child(
640 VpnInstanceOpDataEntry.class, new VpnInstanceOpDataEntryKey(rd));
641 Optional<VpnInstanceOpDataEntry> vpnInstanceOpData = read(LogicalDatastoreType.OPERATIONAL, id);
642 if(vpnInstanceOpData.isPresent()) {
643 return vpnInstanceOpData.get();
648 public void processNodeAdd(BigInteger dpnId) {
649 LOG.debug("Received notification to install TableMiss entries for dpn {} ", dpnId);
650 makeTableMissFlow(dpnId, NwConstants.ADD_FLOW);
651 makeProtocolTableFlow(dpnId, NwConstants.ADD_FLOW);
652 makeL3IntfTblMissFlow(dpnId, NwConstants.ADD_FLOW);
655 private void makeTableMissFlow(BigInteger dpnId, int addOrRemove) {
656 final BigInteger COOKIE_TABLE_MISS = new BigInteger("1030000", 16);
657 // Instruction to goto L3 InterfaceTable
658 List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
659 instructions.add(new InstructionInfo(InstructionType.goto_table, new long[] { L3_INTERFACE_TABLE }));
660 List<MatchInfo> matches = new ArrayList<MatchInfo>();
661 FlowEntity flowEntityLfib = MDSALUtil.buildFlowEntity(dpnId, L3_LFIB_TABLE,
662 getFlowRef(dpnId, L3_LFIB_TABLE, NwConstants.TABLE_MISS_FLOW),
663 NwConstants.TABLE_MISS_PRIORITY, "Table Miss", 0, 0, COOKIE_TABLE_MISS, matches, instructions);
665 FlowEntity flowEntityFib = MDSALUtil.buildFlowEntity(dpnId,L3_FIB_TABLE, getFlowRef(dpnId, L3_FIB_TABLE, NwConstants.TABLE_MISS_FLOW),
666 NwConstants.TABLE_MISS_PRIORITY, "FIB Table Miss Flow", 0, 0, COOKIE_VM_FIB_TABLE,
667 matches, instructions);
669 if (addOrRemove == NwConstants.ADD_FLOW) {
670 LOG.debug("Invoking MDSAL to install Table Miss Entries");
671 mdsalManager.installFlow(flowEntityLfib);
672 mdsalManager.installFlow(flowEntityFib);
674 mdsalManager.removeFlow(flowEntityLfib);
675 mdsalManager.removeFlow(flowEntityFib);
680 private String getFlowRef(BigInteger dpnId, short tableId, int tableMiss) {
681 return new StringBuffer().append(FLOWID_PREFIX).append(dpnId).append(NwConstants.FLOWID_SEPARATOR)
682 .append(tableId).append(NwConstants.FLOWID_SEPARATOR).append(tableMiss)
683 .append(FLOWID_PREFIX).toString();
687 * Install flow entry in protocol table to forward mpls
688 * coming through gre tunnel to LFIB table.
690 private void makeProtocolTableFlow(BigInteger dpnId, int addOrRemove) {
691 final BigInteger COOKIE_PROTOCOL_TABLE = new BigInteger("1070000", 16);
692 // Instruction to goto L3 InterfaceTable
693 List<InstructionInfo> instructions = new ArrayList<>();
694 instructions.add(new InstructionInfo(InstructionType.goto_table, new long[] {L3_LFIB_TABLE}));
695 List<MatchInfo> matches = new ArrayList<MatchInfo>();
696 matches.add(new MatchInfo(MatchFieldType.eth_type,
697 new long[] { 0x8847L }));
698 FlowEntity flowEntityToLfib = MDSALUtil.buildFlowEntity(dpnId, L3_PROTOCOL_TABLE,
699 getFlowRef(dpnId, L3_PROTOCOL_TABLE,
701 DEFAULT_FIB_FLOW_PRIORITY,
702 "Protocol Table For LFIB",
704 COOKIE_PROTOCOL_TABLE,
705 matches, instructions);
707 if (addOrRemove == NwConstants.ADD_FLOW) {
708 LOG.debug("Invoking MDSAL to install Protocol Entries for dpn {}", dpnId);
709 mdsalManager.installFlow(flowEntityToLfib);
711 mdsalManager.removeFlow(flowEntityToLfib);
715 public List<String> printFibEntries() {
716 List<String> result = new ArrayList<String>();
717 result.add(String.format(" %-7s %-20s %-20s %-7s", "RD", "Prefix", "Nexthop", "Label"));
718 result.add("-------------------------------------------------------------------");
719 InstanceIdentifier<FibEntries> id = InstanceIdentifier.create(FibEntries.class);
720 Optional<FibEntries> fibEntries = read(LogicalDatastoreType.OPERATIONAL, id);
721 if (fibEntries.isPresent()) {
722 List<VrfTables> vrfTables = fibEntries.get().getVrfTables();
723 for (VrfTables vrfTable : vrfTables) {
724 for (VrfEntry vrfEntry : vrfTable.getVrfEntry()) {
725 result.add(String.format(" %-7s %-20s %-20s %-7s", vrfTable.getRouteDistinguisher(),
726 vrfEntry.getDestPrefix(), vrfEntry.getNextHopAddress(), vrfEntry.getLabel()));
733 private void makeL3IntfTblMissFlow(BigInteger dpnId, int addOrRemove) {
734 List<InstructionInfo> instructions = new ArrayList<InstructionInfo>();
735 List<MatchInfo> matches = new ArrayList<MatchInfo>();
736 final BigInteger COOKIE_TABLE_MISS = new BigInteger("1030000", 16);
737 // Instruction to clear metadata except SI and LportTag bits
738 instructions.add(new InstructionInfo(InstructionType.write_metadata, new BigInteger[] {
739 CLEAR_METADATA, METADATA_MASK_CLEAR }));
740 // Instruction to clear action
741 instructions.add(new InstructionInfo(InstructionType.clear_actions));
742 // Instruction to goto L3 InterfaceTable
744 instructions.add(new InstructionInfo(InstructionType.goto_table, new long[] { LPORT_DISPATCHER_TABLE }));
746 FlowEntity flowEntityL3Intf = MDSALUtil.buildFlowEntity(dpnId, L3_INTERFACE_TABLE,
747 getFlowRef(dpnId, L3_INTERFACE_TABLE, NwConstants.TABLE_MISS_FLOW),
748 NwConstants.TABLE_MISS_PRIORITY, "L3 Interface Table Miss", 0, 0, COOKIE_TABLE_MISS, matches, instructions);
749 if (addOrRemove == NwConstants.ADD_FLOW) {
750 LOG.info("Invoking MDSAL to install L3 interface Table Miss Entries");
751 mdsalManager.installFlow(flowEntityL3Intf);
753 mdsalManager.removeFlow(flowEntityL3Intf);