2 * Copyright (c) 2015 Cisco Systems, Inc. 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.protocol.bgp.rib.impl;
10 import static com.google.common.base.Verify.verify;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
13 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ADJRIBIN_ATTRIBUTES_AID;
14 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ADJRIBIN_NID;
15 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ATTRIBUTES_NID;
16 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.EFFRIBIN_NID;
17 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.LLGR_STALE_NID;
18 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ROUTES_NID;
19 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.TABLES_NID;
20 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.UPTODATE_NID;
22 import com.google.common.collect.ImmutableList;
23 import com.google.common.collect.ImmutableMap;
24 import com.google.common.collect.ImmutableSet;
25 import com.google.common.util.concurrent.FluentFuture;
26 import com.google.common.util.concurrent.FutureCallback;
27 import com.google.common.util.concurrent.MoreExecutors;
28 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
29 import java.util.Collection;
30 import java.util.List;
32 import java.util.Optional;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.atomic.LongAdder;
36 import org.checkerframework.checker.lock.qual.GuardedBy;
37 import org.checkerframework.checker.lock.qual.Holding;
38 import org.opendaylight.mdsal.common.api.CommitInfo;
39 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
40 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
41 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
43 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
44 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
45 import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
46 import org.opendaylight.protocol.bgp.parser.impl.message.update.CommunityUtil;
47 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
48 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
49 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
50 import org.opendaylight.protocol.bgp.rib.impl.spi.RibOutRefresh;
51 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesInstalledCounters;
52 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesReceivedCounters;
53 import org.opendaylight.protocol.bgp.rib.spi.RIBNormalizedNodes;
54 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
55 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRibRoutingPolicy;
56 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryImportParameters;
57 import org.opendaylight.protocol.bgp.route.targetcontrain.spi.ClientRouteTargetContrainCache;
58 import org.opendaylight.protocol.bgp.route.targetcontrain.spi.RouteTargetMembeshipUtil;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.Attributes;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.attributes.Communities;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerRole;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.route.target.constrain.rev180618.RouteTargetConstrainSubsequentAddressFamily;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.route.target.constrain.rev180618.route.target.constrain.routes.route.target.constrain.routes.RouteTargetConstrainRoute;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.Ipv4AddressFamily;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.Ipv6AddressFamily;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.MplsLabeledVpnSubsequentAddressFamily;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.RouteTarget;
69 import org.opendaylight.yangtools.concepts.ListenerRegistration;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
72 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
73 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
76 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
82 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
83 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
88 * Implementation of the BGP import policy. Listens on peer's Adj-RIB-In, inspects all inbound
89 * routes in the context of the advertising peer's role and applies the inbound policy.
92 * Inbound policy is applied as follows:
95 * 1) if the peer is an eBGP peer, perform attribute replacement and filtering
96 * 2) check if a route is admissible based on attributes attached to it, as well as the
97 * advertising peer's role
98 * 3) output admitting routes with edited attributes into /bgp-rib/rib/peer/effective-rib-in/tables/routes
101 * This class is NOT thread-safe.
103 final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesInstalledCounters,
104 AutoCloseable, ClusteredDOMDataTreeChangeListener {
106 private static final Logger LOG = LoggerFactory.getLogger(EffectiveRibInWriter.class);
107 private static final TablesKey IVP4_VPN_TABLE_KEY = new TablesKey(Ipv4AddressFamily.class,
108 MplsLabeledVpnSubsequentAddressFamily.class);
109 private static final TablesKey IVP6_VPN_TABLE_KEY = new TablesKey(Ipv6AddressFamily.class,
110 MplsLabeledVpnSubsequentAddressFamily.class);
111 private static final ImmutableList<Communities> STALE_LLGR_COMMUNUTIES = ImmutableList.of(
112 StaleCommunities.STALE_LLGR);
113 private static final Attributes STALE_LLGR_ATTRIBUTES = new org.opendaylight.yang.gen.v1.urn.opendaylight.params
114 .xml.ns.yang.bgp.message.rev200120.path.attributes.AttributesBuilder()
115 .setCommunities(STALE_LLGR_COMMUNUTIES)
117 private static final ChoiceNode EMPTY_ROUTES = Builders.choiceBuilder().withNodeIdentifier(ROUTES_NID).build();
119 private final RIBSupportContextRegistry registry;
120 private final YangInstanceIdentifier peerIId;
121 private final YangInstanceIdentifier effRibTables;
122 private final DOMDataTreeChangeService service;
123 private final List<RouteTarget> rtMemberships;
124 private final RibOutRefresh vpnTableRefresher;
125 private final ClientRouteTargetContrainCache rtCache;
126 private ListenerRegistration<?> reg;
127 private DOMTransactionChain chain;
128 private final Map<TablesKey, LongAdder> prefixesReceived;
129 private final Map<TablesKey, LongAdder> prefixesInstalled;
130 private final BGPRibRoutingPolicy ribPolicies;
131 private final BGPRouteEntryImportParameters peerImportParameters;
132 private final BGPTableTypeRegistryConsumer tableTypeRegistry;
134 private FluentFuture<? extends CommitInfo> submitted;
135 private boolean rtMembershipsUpdated;
137 EffectiveRibInWriter(
138 final BGPRouteEntryImportParameters peer,
140 final DOMTransactionChain chain,
141 final YangInstanceIdentifier peerIId,
142 final Set<TablesKey> tables,
143 final BGPTableTypeRegistryConsumer tableTypeRegistry,
144 final List<RouteTarget> rtMemberships,
145 final ClientRouteTargetContrainCache rtCache) {
146 this.registry = requireNonNull(rib.getRibSupportContext());
147 this.chain = requireNonNull(chain);
148 this.peerIId = requireNonNull(peerIId);
149 this.effRibTables = this.peerIId.node(EFFRIBIN_NID);
150 this.prefixesInstalled = buildPrefixesTables(tables);
151 this.prefixesReceived = buildPrefixesTables(tables);
152 this.ribPolicies = requireNonNull(rib.getRibPolicies());
153 this.service = requireNonNull(rib.getService());
154 this.tableTypeRegistry = requireNonNull(tableTypeRegistry);
155 this.peerImportParameters = peer;
156 this.rtMemberships = rtMemberships;
157 this.rtCache = rtCache;
158 this.vpnTableRefresher = rib;
162 final DOMDataTreeIdentifier treeId = new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL,
163 this.peerIId.node(ADJRIBIN_NID).node(TABLES_NID));
164 LOG.debug("Registered Effective RIB on {}", this.peerIId);
165 this.reg = requireNonNull(this.service).registerDataTreeChangeListener(treeId, this);
168 private static Map<TablesKey, LongAdder> buildPrefixesTables(final Set<TablesKey> tables) {
169 final ImmutableMap.Builder<TablesKey, LongAdder> b = ImmutableMap.builder();
170 tables.forEach(table -> b.put(table, new LongAdder()));
175 public synchronized void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
176 if (this.chain == null) {
177 LOG.trace("Chain closed. Ignoring Changes : {}", changes);
181 LOG.trace("Data changed called to effective RIB. Change : {}", changes);
182 DOMDataTreeWriteTransaction tx = null;
183 for (final DataTreeCandidate tc : changes) {
184 final YangInstanceIdentifier rootPath = tc.getRootPath();
185 final DataTreeCandidateNode root = tc.getRootNode();
186 for (final DataTreeCandidateNode table : root.getChildNodes()) {
188 tx = this.chain.newWriteOnlyTransaction();
190 changeDataTree(tx, rootPath, root, table);
195 final FluentFuture<? extends CommitInfo> future = tx.commit();
196 this.submitted = future;
197 future.addCallback(new FutureCallback<CommitInfo>() {
199 public void onSuccess(final CommitInfo result) {
200 LOG.trace("Successful commit");
204 public void onFailure(final Throwable trw) {
205 LOG.error("Failed commit", trw);
207 }, MoreExecutors.directExecutor());
210 //Refresh VPN Table if RT Memberships were updated
211 if (this.rtMembershipsUpdated) {
212 this.vpnTableRefresher.refreshTable(IVP4_VPN_TABLE_KEY, this.peerImportParameters.getFromPeerId());
213 this.vpnTableRefresher.refreshTable(IVP6_VPN_TABLE_KEY, this.peerImportParameters.getFromPeerId());
214 this.rtMembershipsUpdated = false;
219 public synchronized void close() {
220 if (this.reg != null) {
224 if (this.submitted != null) {
226 this.submitted.get();
227 } catch (final InterruptedException | ExecutionException throwable) {
228 LOG.error("Write routes failed", throwable);
231 if (this.chain != null) {
235 this.prefixesReceived.values().forEach(LongAdder::reset);
236 this.prefixesInstalled.values().forEach(LongAdder::reset);
240 public long getPrefixedReceivedCount(final TablesKey tablesKey) {
241 final LongAdder counter = this.prefixesReceived.get(tablesKey);
242 if (counter == null) {
245 return counter.longValue();
249 public Set<TablesKey> getTableKeys() {
250 return ImmutableSet.copyOf(this.prefixesReceived.keySet());
254 public boolean isSupported(final TablesKey tablesKey) {
255 return this.prefixesReceived.containsKey(tablesKey);
259 public long getPrefixedInstalledCount(final TablesKey tablesKey) {
260 final LongAdder counter = this.prefixesInstalled.get(tablesKey);
261 if (counter == null) {
264 return counter.longValue();
268 public long getTotalPrefixesInstalled() {
269 return this.prefixesInstalled.values().stream().mapToLong(LongAdder::longValue).sum();
273 private void changeDataTree(final DOMDataTreeWriteTransaction tx, final YangInstanceIdentifier rootPath,
274 final DataTreeCandidateNode root, final DataTreeCandidateNode table) {
275 final PathArgument lastArg = table.getIdentifier();
276 verify(lastArg instanceof NodeIdentifierWithPredicates, "Unexpected type %s in path %s", lastArg.getClass(),
278 final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
279 final RIBSupportContext ribContext = this.registry.getRIBSupportContext(tableKey);
280 if (ribContext == null) {
281 LOG.warn("Table {} is not supported, ignoring event", tableKey);
285 final YangInstanceIdentifier effectiveTablePath = effectiveTablePath(tableKey);
286 final ModificationType modificationType = root.getModificationType();
287 LOG.debug("Effective table {} modification type {}", effectiveTablePath, modificationType);
288 switch (modificationType) {
291 deleteTable(tx, ribContext, effectiveTablePath, table);
295 writeTable(tx, ribContext, effectiveTablePath, table);
297 case SUBTREE_MODIFIED:
298 modifyTable(tx, ribContext, effectiveTablePath, table);
301 LOG.info("Ignoring spurious notification on {} data {}", rootPath, table);
304 LOG.warn("Ignoring unhandled root {}", table);
309 private void deleteTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
310 final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
311 LOG.debug("Delete Effective Table {}", effectiveTablePath);
312 onDeleteTable(ribContext.getRibSupport(), effectiveTablePath, table.getDataBefore());
313 tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath);
316 private void modifyTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
317 final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
318 LOG.debug("Modify Effective Table {}", effectiveTablePath);
320 final boolean wasLongLivedStale = isLongLivedStaleTable(table.getDataBefore());
321 final boolean longLivedStale = isLongLivedStaleTable(table.getDataAfter());
322 if (wasLongLivedStale != longLivedStale) {
323 LOG.debug("LLGR_STALE flag flipped {}, overwriting table {}", longLivedStale ? "ON" : "OFF",
325 writeTable(tx, ribContext, effectiveTablePath, table);
329 table.getModifiedChild(ATTRIBUTES_NID).ifPresent(modifiedAttrs -> {
330 final YangInstanceIdentifier effAttrsPath = effectiveTablePath.node(ATTRIBUTES_NID);
331 final Optional<NormalizedNode<?, ?>> optAttrsAfter = modifiedAttrs.getDataAfter();
332 if (optAttrsAfter.isPresent()) {
333 tx.put(LogicalDatastoreType.OPERATIONAL, effAttrsPath, effectiveAttributes(
334 NormalizedNodes.findNode(optAttrsAfter.get(), UPTODATE_NID)));
336 tx.delete(LogicalDatastoreType.OPERATIONAL, effAttrsPath);
340 table.getModifiedChild(ROUTES_NID).ifPresent(modifiedRoutes -> {
341 final RIBSupport<?, ?, ?, ?> ribSupport = ribContext.getRibSupport();
342 switch (modifiedRoutes.getModificationType()) {
345 deleteRoutesBefore(tx, ribSupport, effectiveTablePath, modifiedRoutes);
346 // XXX: YANG Tools seems to have an issue stacking DELETE with child WRITE
347 tx.put(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ROUTES_NID), EMPTY_ROUTES);
348 writeRoutesAfter(tx, ribSupport, effectiveTablePath, modifiedRoutes.getDataAfter(), longLivedStale);
352 deleteRoutesBefore(tx, ribSupport, effectiveTablePath, modifiedRoutes);
353 tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ROUTES_NID));
355 case SUBTREE_MODIFIED:
356 for (DataTreeCandidateNode modifiedRoute : ribSupport.changedRoutes(modifiedRoutes)) {
357 processRoute(tx, ribSupport, effectiveTablePath, modifiedRoute, longLivedStale);
364 LOG.warn("Ignoring modified routes {}", modifiedRoutes);
370 private void writeTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
371 final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
372 LOG.debug("Write Effective Table {}", effectiveTablePath);
373 onDeleteTable(ribContext.getRibSupport(), effectiveTablePath, table.getDataBefore());
375 final Optional<NormalizedNode<?, ?>> maybeTableAfter = table.getDataAfter();
376 if (maybeTableAfter.isPresent()) {
377 final MapEntryNode tableAfter = extractMapEntry(maybeTableAfter);
378 ribContext.createEmptyTableStructure(tx, effectiveTablePath);
380 final Optional<DataContainerChild<?, ?>> maybeAttrsAfter = tableAfter.getChild(ATTRIBUTES_NID);
381 final boolean longLivedStale;
382 if (maybeAttrsAfter.isPresent()) {
383 final ContainerNode attrsAfter = extractContainer(maybeAttrsAfter);
384 longLivedStale = isLongLivedStale(attrsAfter);
385 tx.put(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ATTRIBUTES_NID),
386 effectiveAttributes(attrsAfter.getChild(UPTODATE_NID)));
388 longLivedStale = false;
391 writeRoutesAfter(tx, ribContext.getRibSupport(), effectiveTablePath,
392 NormalizedNodes.findNode(tableAfter, ROUTES_NID), longLivedStale);
396 // Performs house-keeping when the contents of a table is deleted
397 private void onDeleteTable(final RIBSupport<?, ?, ?, ?> ribSupport, final YangInstanceIdentifier effectiveTablePath,
398 final Optional<NormalizedNode<?, ?>> tableBefore) {
399 // Routes are special in that we need to process the to keep our counters accurate
400 final Optional<NormalizedNode<?, ?>> maybeRoutesBefore = findRoutesMap(ribSupport,
401 NormalizedNodes.findNode(tableBefore, ROUTES_NID));
402 if (maybeRoutesBefore.isPresent()) {
403 onRoutesDeleted(ribSupport, effectiveTablePath, extractMap(maybeRoutesBefore).getValue());
407 private void deleteRoutesBefore(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?, ?, ?> ribSupport,
408 final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode modifiedRoutes) {
409 final Optional<NormalizedNode<?, ?>> maybeRoutesBefore = NormalizedNodes.findNode(
410 modifiedRoutes.getDataBefore(), ribSupport.relativeRoutesPath());
411 if (maybeRoutesBefore.isPresent()) {
412 onRoutesDeleted(ribSupport, effectiveTablePath, extractMap(maybeRoutesBefore).getValue());
416 private void writeRoutesAfter(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?, ?, ?> ribSupport,
417 final YangInstanceIdentifier effectiveTablePath, final Optional<NormalizedNode<?, ?>> routesAfter,
418 final boolean longLivedStale) {
419 final Optional<NormalizedNode<?, ?>> maybeRoutesAfter = NormalizedNodes.findNode(routesAfter,
420 ribSupport.relativeRoutesPath());
421 if (maybeRoutesAfter.isPresent()) {
422 final YangInstanceIdentifier routesPath = routeMapPath(ribSupport, effectiveTablePath);
423 for (MapEntryNode routeAfter : extractMap(maybeRoutesAfter).getValue()) {
424 writeRoute(tx, ribSupport, routesPath.node(routeAfter.getIdentifier()), Optional.empty(), routeAfter,
430 private void onRoutesDeleted(final RIBSupport<?, ?, ?, ?> ribSupport,
431 final YangInstanceIdentifier effectiveTablePath, final Collection<MapEntryNode> deletedRoutes) {
432 if (ribSupport.getSafi() == RouteTargetConstrainSubsequentAddressFamily.class) {
433 final YangInstanceIdentifier routesPath = routeMapPath(ribSupport, effectiveTablePath);
434 for (final MapEntryNode routeBefore : deletedRoutes) {
435 deleteRouteTarget(ribSupport, routesPath.node(routeBefore.getIdentifier()), routeBefore);
437 this.rtMembershipsUpdated = true;
440 final TablesKey tablesKey = ribSupport.getTablesKey();
441 CountersUtil.add(prefixesInstalled.get(tablesKey), tablesKey, -deletedRoutes.size());
444 private void processRoute(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?, ?, ?> ribSupport,
445 final YangInstanceIdentifier routesPath, final DataTreeCandidateNode route, final boolean longLivedStale) {
446 LOG.debug("Process route {}", route.getIdentifier());
447 final YangInstanceIdentifier routePath = ribSupport.routePath(routesPath, route.getIdentifier());
448 switch (route.getModificationType()) {
451 deleteRoute(tx, ribSupport, routePath, route.getDataBefore().orElse(null));
457 case SUBTREE_MODIFIED:
459 writeRoute(tx, ribSupport, routePath, route.getDataBefore(), route.getDataAfter().get(),
463 LOG.warn("Ignoring unhandled route {}", route);
468 private void deleteRoute(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?, ?, ?> ribSupport,
469 final YangInstanceIdentifier routeIdPath, final NormalizedNode<?, ?> route) {
470 handleRouteTarget(ModificationType.DELETE, ribSupport, routeIdPath, route);
471 tx.delete(LogicalDatastoreType.OPERATIONAL, routeIdPath);
472 LOG.debug("Route deleted. routeId={}", routeIdPath);
473 final TablesKey tablesKey = ribSupport.getTablesKey();
474 CountersUtil.decrement(this.prefixesInstalled.get(tablesKey), tablesKey);
477 private void writeRoute(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?, ?, ?> ribSupport,
478 final YangInstanceIdentifier routePath, final Optional<NormalizedNode<?, ?>> routeBefore,
479 final NormalizedNode<?, ?> routeAfter, final boolean longLivedStale) {
480 final TablesKey tablesKey = ribSupport.getTablesKey();
481 CountersUtil.increment(this.prefixesReceived.get(tablesKey), tablesKey);
482 // Lookup per-table attributes from RIBSupport
483 final ContainerNode advertisedAttrs = (ContainerNode) NormalizedNodes.findNode(routeAfter,
484 ribSupport.routeAttributesIdentifier()).orElse(null);
485 final Attributes routeAttrs = ribSupport.attributeFromContainerNode(advertisedAttrs);
486 final Optional<Attributes> optEffAtt;
487 // In case we want to add LLGR_STALE we do not process route through policies since it may be
488 // considered as received with LLGR_STALE from peer which is not true.
489 if (longLivedStale) {
490 // LLGR procedures are in effect. If the route is tagged with NO_LLGR, it needs to be removed.
491 final List<Communities> effCommunities = routeAttrs.getCommunities();
492 if (effCommunities != null && effCommunities.contains(CommunityUtil.NO_LLGR)) {
493 deleteRoute(tx, ribSupport, routePath, routeBefore.orElse(null));
496 optEffAtt = Optional.of(wrapLongLivedStale(routeAttrs));
498 optEffAtt = ribPolicies.applyImportPolicies(peerImportParameters, routeAttrs,
499 verifyNotNull(tableTypeRegistry.getAfiSafiType(ribSupport.getTablesKey())));
501 if (!optEffAtt.isPresent()) {
502 deleteRoute(tx, ribSupport, routePath, routeBefore.orElse(null));
505 handleRouteTarget(ModificationType.WRITE, ribSupport, routePath, routeAfter);
506 tx.put(LogicalDatastoreType.OPERATIONAL, routePath, routeAfter);
507 CountersUtil.increment(this.prefixesInstalled.get(tablesKey), tablesKey);
509 final YangInstanceIdentifier attPath = routePath.node(ribSupport.routeAttributesIdentifier());
510 final Attributes attToStore = optEffAtt.get();
511 if (!attToStore.equals(routeAttrs)) {
512 final ContainerNode finalAttribute = ribSupport.attributeToContainerNode(attPath, attToStore);
513 tx.put(LogicalDatastoreType.OPERATIONAL, attPath, finalAttribute);
517 private void addRouteTarget(final RouteTargetConstrainRoute rtc) {
518 final RouteTarget rtMembership = RouteTargetMembeshipUtil.getRT(rtc);
519 if (PeerRole.Ebgp != this.peerImportParameters.getFromPeerRole()) {
520 this.rtCache.cacheRoute(rtc);
522 this.rtMemberships.add(rtMembership);
525 private void deleteRouteTarget(final RIBSupport<?, ?, ?, ?> ribSupport, final YangInstanceIdentifier routeIdPath,
526 final NormalizedNode<?, ?> route) {
527 deleteRouteTarget((RouteTargetConstrainRoute) ribSupport.fromNormalizedNode(routeIdPath, route));
530 private void deleteRouteTarget(final RouteTargetConstrainRoute rtc) {
531 final RouteTarget rtMembership = RouteTargetMembeshipUtil.getRT(rtc);
532 if (PeerRole.Ebgp != this.peerImportParameters.getFromPeerRole()) {
533 this.rtCache.uncacheRoute(rtc);
535 this.rtMemberships.remove(rtMembership);
538 private void handleRouteTarget(final ModificationType modificationType, final RIBSupport<?, ?, ?, ?> ribSupport,
539 final YangInstanceIdentifier routeIdPath, final NormalizedNode<?, ?> route) {
540 if (ribSupport.getSafi() == RouteTargetConstrainSubsequentAddressFamily.class) {
541 final RouteTargetConstrainRoute rtc =
542 (RouteTargetConstrainRoute) ribSupport.fromNormalizedNode(routeIdPath, route);
543 if (ModificationType.DELETE == modificationType) {
544 deleteRouteTarget(rtc);
548 this.rtMembershipsUpdated = true;
552 @SuppressFBWarnings("UPM_UNCALLED_PRIVATE_METHOD")
553 private static Attributes wrapLongLivedStale(final Attributes attrs) {
555 return STALE_LLGR_ATTRIBUTES;
558 final List<Communities> oldCommunities = attrs.getCommunities();
559 final List<Communities> newCommunities;
560 if (oldCommunities != null) {
561 if (oldCommunities.contains(StaleCommunities.STALE_LLGR)) {
564 newCommunities = StaleCommunities.create(oldCommunities);
566 newCommunities = STALE_LLGR_COMMUNUTIES;
569 return new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120
570 .path.attributes.AttributesBuilder(attrs).setCommunities(newCommunities).build();
573 // XXX: this should be moved to YangInstanceIdentifier at some point
574 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
575 YangInstanceIdentifier ret = parent;
576 for (PathArgument arg : args) {
582 private YangInstanceIdentifier effectiveTablePath(final NodeIdentifierWithPredicates tableKey) {
583 return this.effRibTables.node(TABLES_NID).node(tableKey);
586 private static YangInstanceIdentifier routeMapPath(final RIBSupport<?, ?, ?, ?> ribSupport,
587 final YangInstanceIdentifier tablePath) {
588 return concat(tablePath.node(ROUTES_NID), ribSupport.relativeRoutesPath());
591 private static Optional<NormalizedNode<?, ?>> findRoutesMap(final RIBSupport<?, ?, ?, ?> ribSupport,
592 final Optional<NormalizedNode<?, ?>> optRoutes) {
593 return NormalizedNodes.findNode(optRoutes, ribSupport.relativeRoutesPath());
596 private static ContainerNode extractContainer(final Optional<? extends NormalizedNode<?, ?>> optNode) {
597 final NormalizedNode<?, ?> node = optNode.get();
598 verify(node instanceof ContainerNode, "Expected ContainerNode, got %s", node);
599 return (ContainerNode) node;
602 private static MapNode extractMap(final Optional<? extends NormalizedNode<?, ?>> optNode) {
603 final NormalizedNode<?, ?> node = optNode.get();
604 verify(node instanceof MapNode, "Expected MapNode, got %s", node);
605 return (MapNode) node;
608 private static MapEntryNode extractMapEntry(final Optional<? extends NormalizedNode<?, ?>> optNode) {
609 final NormalizedNode<?, ?> node = optNode.get();
610 verify(node instanceof MapEntryNode, "Expected MapEntryNode, got %s", node);
611 return (MapEntryNode) node;
614 private static boolean isLongLivedStale(final ContainerNode attributes) {
615 return NormalizedNodes.findNode(attributes, ADJRIBIN_ATTRIBUTES_AID, LLGR_STALE_NID).isPresent();
618 private static boolean isLongLivedStaleTable(final Optional<NormalizedNode<?, ?>> optTable) {
619 final Optional<NormalizedNode<?, ?>> optAttributes = NormalizedNodes.findNode(optTable, ATTRIBUTES_NID);
620 return optAttributes.isPresent() && isLongLivedStale(extractContainer(optAttributes));
623 private static ContainerNode effectiveAttributes(final Optional<? extends NormalizedNode<?, ?>> optUptodate) {
624 return optUptodate.map(leaf -> {
625 final Object value = leaf.getValue();
626 verify(value instanceof Boolean, "Expected boolean uptodate, got %s", value);
627 return ((Boolean) value).booleanValue() ? RIBNormalizedNodes.UPTODATE_ATTRIBUTES
628 : RIBNormalizedNodes.NOT_UPTODATE_ATTRIBUTES;
629 }).orElse(RIBNormalizedNodes.NOT_UPTODATE_ATTRIBUTES);