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_NID;
14 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ATTRIBUTES_NID;
15 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.EFFRIBIN_NID;
16 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.LLGR_STALE_NID;
17 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ROUTES_NID;
18 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.TABLES_NID;
19 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.UPTODATE_NID;
21 import com.google.common.collect.ImmutableList;
22 import com.google.common.collect.ImmutableMap;
23 import com.google.common.collect.ImmutableSet;
24 import com.google.common.util.concurrent.FluentFuture;
25 import com.google.common.util.concurrent.FutureCallback;
26 import com.google.common.util.concurrent.MoreExecutors;
27 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
28 import java.util.Collection;
29 import java.util.List;
31 import java.util.Optional;
33 import java.util.concurrent.ExecutionException;
34 import java.util.concurrent.atomic.LongAdder;
35 import org.checkerframework.checker.lock.qual.GuardedBy;
36 import org.checkerframework.checker.lock.qual.Holding;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.eclipse.jdt.annotation.Nullable;
39 import org.opendaylight.mdsal.common.api.CommitInfo;
40 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
41 import org.opendaylight.mdsal.dom.api.DOMDataBroker.DataTreeChangeExtension;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
43 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
44 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
45 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
46 import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
47 import org.opendaylight.protocol.bgp.parser.impl.message.update.CommunityUtil;
48 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
49 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
50 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
51 import org.opendaylight.protocol.bgp.rib.impl.spi.RibOutRefresh;
52 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesInstalledCounters;
53 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesReceivedCounters;
54 import org.opendaylight.protocol.bgp.rib.spi.RIBNormalizedNodes;
55 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
56 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRibRoutingPolicy;
57 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryImportParameters;
58 import org.opendaylight.protocol.bgp.route.targetcontrain.spi.ClientRouteTargetContrainCache;
59 import org.opendaylight.protocol.bgp.route.targetcontrain.spi.RouteTargetMembeshipUtil;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.Attributes;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.attributes.Communities;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerRole;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.route.target.constrain.rev180618.RouteTargetConstrainSubsequentAddressFamily;
65 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;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.Ipv4AddressFamily;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.Ipv6AddressFamily;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.MplsLabeledVpnSubsequentAddressFamily;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.RouteTarget;
70 import org.opendaylight.yangtools.concepts.Registration;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
72 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
73 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
74 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
77 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
80 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
81 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
82 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
83 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateNode;
84 import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
89 * Implementation of the BGP import policy. Listens on peer's Adj-RIB-In, inspects all inbound
90 * routes in the context of the advertising peer's role and applies the inbound policy.
93 * Inbound policy is applied as follows:
96 * 1) if the peer is an eBGP peer, perform attribute replacement and filtering
97 * 2) check if a route is admissible based on attributes attached to it, as well as the
98 * advertising peer's role
99 * 3) output admitting routes with edited attributes into /bgp-rib/rib/peer/effective-rib-in/tables/routes
102 * This class is NOT thread-safe.
104 final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesInstalledCounters,
105 AutoCloseable, DOMDataTreeChangeListener {
106 private static final Logger LOG = LoggerFactory.getLogger(EffectiveRibInWriter.class);
107 private static final TablesKey IVP4_VPN_TABLE_KEY =
108 new TablesKey(Ipv4AddressFamily.VALUE, MplsLabeledVpnSubsequentAddressFamily.VALUE);
109 private static final TablesKey IVP6_VPN_TABLE_KEY =
110 new TablesKey(Ipv6AddressFamily.VALUE, MplsLabeledVpnSubsequentAddressFamily.VALUE);
111 private static final ImmutableList<Communities> STALE_LLGR_COMMUNUTIES =
112 ImmutableList.of(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 DataTreeChangeExtension service;
123 private final List<RouteTarget> rtMemberships;
124 private final RibOutRefresh vpnTableRefresher;
125 private final ClientRouteTargetContrainCache rtCache;
126 private Registration 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 registry = requireNonNull(rib.getRibSupportContext());
147 this.chain = requireNonNull(chain);
148 this.peerIId = requireNonNull(peerIId);
149 effRibTables = this.peerIId.node(EFFRIBIN_NID);
150 prefixesInstalled = buildPrefixesTables(tables);
151 prefixesReceived = buildPrefixesTables(tables);
152 ribPolicies = requireNonNull(rib.getRibPolicies());
153 service = requireNonNull(rib.getService());
154 this.tableTypeRegistry = requireNonNull(tableTypeRegistry);
155 peerImportParameters = peer;
156 this.rtMemberships = rtMemberships;
157 this.rtCache = rtCache;
158 vpnTableRefresher = rib;
162 final DOMDataTreeIdentifier treeId = DOMDataTreeIdentifier.of(LogicalDatastoreType.OPERATIONAL,
163 peerIId.node(ADJRIBIN_NID).node(TABLES_NID));
164 LOG.debug("Registered Effective RIB on {}", peerIId);
165 reg = requireNonNull(service).registerTreeChangeListener(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 onInitialData() {
176 // FIXME: update as if root was deleted
180 public synchronized void onDataTreeChanged(final List<DataTreeCandidate> changes) {
182 LOG.trace("Chain closed. Ignoring Changes : {}", changes);
186 LOG.trace("Data changed called to effective RIB. Change : {}", changes);
187 DOMDataTreeWriteTransaction tx = null;
188 for (final DataTreeCandidate tc : changes) {
189 final YangInstanceIdentifier rootPath = tc.getRootPath();
190 final DataTreeCandidateNode root = tc.getRootNode();
191 for (final DataTreeCandidateNode table : root.childNodes()) {
193 tx = chain.newWriteOnlyTransaction();
195 changeDataTree(tx, rootPath, root, table);
200 final FluentFuture<? extends CommitInfo> future = tx.commit();
202 future.addCallback(new FutureCallback<CommitInfo>() {
204 public void onSuccess(final CommitInfo result) {
205 LOG.trace("Successful commit");
209 public void onFailure(final Throwable trw) {
210 LOG.error("Failed commit", trw);
212 }, MoreExecutors.directExecutor());
215 //Refresh VPN Table if RT Memberships were updated
216 if (rtMembershipsUpdated) {
217 vpnTableRefresher.refreshTable(IVP4_VPN_TABLE_KEY, peerImportParameters.getFromPeerId());
218 vpnTableRefresher.refreshTable(IVP6_VPN_TABLE_KEY, peerImportParameters.getFromPeerId());
219 rtMembershipsUpdated = false;
224 public synchronized void close() {
229 if (submitted != null) {
232 } catch (final InterruptedException | ExecutionException throwable) {
233 LOG.error("Write routes failed", throwable);
240 prefixesReceived.values().forEach(LongAdder::reset);
241 prefixesInstalled.values().forEach(LongAdder::reset);
245 public long getPrefixedReceivedCount(final TablesKey tablesKey) {
246 final LongAdder counter = prefixesReceived.get(tablesKey);
247 if (counter == null) {
250 return counter.longValue();
254 public Set<TablesKey> getTableKeys() {
255 return ImmutableSet.copyOf(prefixesReceived.keySet());
259 public boolean isSupported(final TablesKey tablesKey) {
260 return prefixesReceived.containsKey(tablesKey);
264 public long getPrefixedInstalledCount(final TablesKey tablesKey) {
265 final LongAdder counter = prefixesInstalled.get(tablesKey);
266 if (counter == null) {
269 return counter.longValue();
273 public long getTotalPrefixesInstalled() {
274 return prefixesInstalled.values().stream().mapToLong(LongAdder::longValue).sum();
278 private void changeDataTree(final DOMDataTreeWriteTransaction tx, final YangInstanceIdentifier rootPath,
279 final DataTreeCandidateNode root, final DataTreeCandidateNode table) {
280 final PathArgument lastArg = table.name();
281 verify(lastArg instanceof NodeIdentifierWithPredicates, "Unexpected type %s in path %s", lastArg.getClass(),
283 final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
284 final RIBSupportContext ribContext = registry.getRIBSupportContext(tableKey);
285 if (ribContext == null) {
286 LOG.warn("Table {} is not supported, ignoring event", tableKey);
290 final YangInstanceIdentifier effectiveTablePath = effectiveTablePath(tableKey);
291 final ModificationType modificationType = root.modificationType();
292 LOG.debug("Effective table {} modification type {}", effectiveTablePath, modificationType);
293 switch (modificationType) {
296 deleteTable(tx, ribContext, effectiveTablePath, table);
300 writeTable(tx, ribContext, effectiveTablePath, table);
302 case SUBTREE_MODIFIED:
303 modifyTable(tx, ribContext, effectiveTablePath, table);
306 LOG.info("Ignoring spurious notification on {} data {}", rootPath, table);
309 LOG.warn("Ignoring unhandled root {}", table);
314 private void deleteTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
315 final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
316 LOG.debug("Delete Effective Table {}", effectiveTablePath);
317 onDeleteTable(ribContext.getRibSupport(), effectiveTablePath, table.dataBefore());
318 tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath);
321 private void modifyTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
322 final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
323 LOG.debug("Modify Effective Table {}", effectiveTablePath);
325 final boolean wasLongLivedStale = isLongLivedStaleTable(table.findDataBefore());
326 final boolean longLivedStale = isLongLivedStaleTable(table.findDataAfter());
327 if (wasLongLivedStale != longLivedStale) {
328 LOG.debug("LLGR_STALE flag flipped {}, overwriting table {}", longLivedStale ? "ON" : "OFF",
330 writeTable(tx, ribContext, effectiveTablePath, table);
334 final var modifiedAttrs = table.modifiedChild(ATTRIBUTES_NID);
335 if (modifiedAttrs != null) {
336 final YangInstanceIdentifier effAttrsPath = effectiveTablePath.node(ATTRIBUTES_NID);
337 final var attrsAfter = modifiedAttrs.dataAfter();
338 if (attrsAfter != null) {
339 tx.put(LogicalDatastoreType.OPERATIONAL, effAttrsPath,
340 effectiveAttributes(extractContainer(attrsAfter)));
342 tx.delete(LogicalDatastoreType.OPERATIONAL, effAttrsPath);
346 final var modifiedRoutes = table.modifiedChild(ROUTES_NID);
347 if (modifiedRoutes != null) {
348 final RIBSupport<?, ?> ribSupport = ribContext.getRibSupport();
349 switch (modifiedRoutes.modificationType()) {
352 deleteRoutesBefore(tx, ribSupport, effectiveTablePath, modifiedRoutes);
353 // XXX: YANG Tools seems to have an issue stacking DELETE with child WRITE
354 tx.put(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ROUTES_NID), EMPTY_ROUTES);
355 writeRoutesAfter(tx, ribSupport, effectiveTablePath, modifiedRoutes.findDataAfter(),
360 deleteRoutesBefore(tx, ribSupport, effectiveTablePath, modifiedRoutes);
361 tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ROUTES_NID));
363 case SUBTREE_MODIFIED:
364 for (DataTreeCandidateNode modifiedRoute : ribSupport.changedRoutes(modifiedRoutes)) {
365 processRoute(tx, ribSupport, effectiveTablePath, modifiedRoute, longLivedStale);
372 LOG.warn("Ignoring modified routes {}", modifiedRoutes);
378 private void writeTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
379 final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
380 LOG.debug("Write Effective Table {}", effectiveTablePath);
381 onDeleteTable(ribContext.getRibSupport(), effectiveTablePath, table.dataBefore());
383 final var node = table.dataAfter();
385 verify(node instanceof MapEntryNode, "Expected MapEntryNode, got %s", node);
386 final MapEntryNode tableAfter = (MapEntryNode) node;
387 ribContext.createEmptyTableStructure(tx, effectiveTablePath);
389 final DataContainerChild maybeAttrsAfter = tableAfter.childByArg(ATTRIBUTES_NID);
390 final boolean longLivedStale;
391 if (maybeAttrsAfter != null) {
392 final ContainerNode attrsAfter = extractContainer(maybeAttrsAfter);
393 longLivedStale = isLongLivedStale(attrsAfter);
394 tx.put(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ATTRIBUTES_NID),
395 effectiveAttributes(attrsAfter));
397 longLivedStale = false;
400 writeRoutesAfter(tx, ribContext.getRibSupport(), effectiveTablePath,
401 NormalizedNodes.findNode(tableAfter, ROUTES_NID), longLivedStale);
405 // Performs house-keeping when the contents of a table is deleted
406 private void onDeleteTable(final RIBSupport<?, ?> ribSupport, final YangInstanceIdentifier effectiveTablePath,
407 final @Nullable NormalizedNode tableBefore) {
408 // Routes are special in that we need to process the to keep our counters accurate
409 final var maybeRoutesBefore = findRoutesMap(ribSupport, NormalizedNodes.findNode(tableBefore, ROUTES_NID));
410 if (maybeRoutesBefore.isPresent()) {
411 onRoutesDeleted(ribSupport, effectiveTablePath, extractMap(maybeRoutesBefore).body());
415 private void deleteRoutesBefore(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?> ribSupport,
416 final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode modifiedRoutes) {
417 final Optional<NormalizedNode> maybeRoutesBefore =
418 NormalizedNodes.findNode(modifiedRoutes.dataBefore(), ribSupport.relativeRoutesPath());
419 if (maybeRoutesBefore.isPresent()) {
420 onRoutesDeleted(ribSupport, effectiveTablePath, extractMap(maybeRoutesBefore).body());
424 private void writeRoutesAfter(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?> ribSupport,
425 final YangInstanceIdentifier effectiveTablePath, final Optional<NormalizedNode> routesAfter,
426 final boolean longLivedStale) {
427 final Optional<NormalizedNode> maybeRoutesAfter = NormalizedNodes.findNode(routesAfter,
428 ribSupport.relativeRoutesPath());
429 if (maybeRoutesAfter.isPresent()) {
430 final YangInstanceIdentifier routesPath = routeMapPath(ribSupport, effectiveTablePath);
431 for (MapEntryNode routeAfter : extractMap(maybeRoutesAfter).body()) {
432 writeRoute(tx, ribSupport, routesPath.node(routeAfter.name()), null, routeAfter, longLivedStale);
437 private void onRoutesDeleted(final RIBSupport<?, ?> ribSupport, final YangInstanceIdentifier effectiveTablePath,
438 final Collection<MapEntryNode> deletedRoutes) {
439 if (RouteTargetConstrainSubsequentAddressFamily.VALUE.equals(ribSupport.getTablesKey().getSafi())) {
440 final YangInstanceIdentifier routesPath = routeMapPath(ribSupport, effectiveTablePath);
441 for (final MapEntryNode routeBefore : deletedRoutes) {
442 deleteRouteTarget(ribSupport, routesPath.node(routeBefore.name()), routeBefore);
444 rtMembershipsUpdated = true;
447 final TablesKey tablesKey = ribSupport.getTablesKey();
448 CountersUtil.add(prefixesInstalled.get(tablesKey), tablesKey, -deletedRoutes.size());
451 private void processRoute(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?> ribSupport,
452 final YangInstanceIdentifier routesPath, final DataTreeCandidateNode route, final boolean longLivedStale) {
453 LOG.debug("Process route {}", route.name());
454 final YangInstanceIdentifier routePath = ribSupport.routePath(routesPath, route.name());
455 switch (route.modificationType()) {
458 deleteRoute(tx, ribSupport, routePath, route.dataBefore());
464 case SUBTREE_MODIFIED:
466 writeRoute(tx, ribSupport, routePath, route.dataBefore(), route.getDataAfter(), longLivedStale);
469 LOG.warn("Ignoring unhandled route {}", route);
474 private void deleteRoute(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?> ribSupport,
475 final YangInstanceIdentifier routeIdPath, final NormalizedNode route) {
476 handleRouteTarget(ModificationType.DELETE, ribSupport, routeIdPath, route);
477 tx.delete(LogicalDatastoreType.OPERATIONAL, routeIdPath);
478 LOG.debug("Route deleted. routeId={}", routeIdPath);
479 final TablesKey tablesKey = ribSupport.getTablesKey();
480 CountersUtil.decrement(prefixesInstalled.get(tablesKey), tablesKey);
483 private void writeRoute(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?> ribSupport,
484 final YangInstanceIdentifier routePath, final @Nullable NormalizedNode routeBefore,
485 final @NonNull NormalizedNode routeAfter, final boolean longLivedStale) {
486 final TablesKey tablesKey = ribSupport.getTablesKey();
487 CountersUtil.increment(prefixesReceived.get(tablesKey), tablesKey);
488 // Lookup per-table attributes from RIBSupport
489 final ContainerNode advertisedAttrs = (ContainerNode) NormalizedNodes.findNode(routeAfter,
490 ribSupport.routeAttributesIdentifier()).orElse(null);
491 final Attributes routeAttrs = ribSupport.attributeFromContainerNode(advertisedAttrs);
492 final Optional<Attributes> optEffAtt;
493 // In case we want to add LLGR_STALE we do not process route through policies since it may be
494 // considered as received with LLGR_STALE from peer which is not true.
495 if (longLivedStale) {
496 // LLGR procedures are in effect. If the route is tagged with NO_LLGR, it needs to be removed.
497 final List<Communities> effCommunities = routeAttrs.getCommunities();
498 if (effCommunities != null && effCommunities.contains(CommunityUtil.NO_LLGR)) {
499 deleteRoute(tx, ribSupport, routePath, routeBefore);
502 optEffAtt = Optional.of(wrapLongLivedStale(routeAttrs));
504 optEffAtt = ribPolicies.applyImportPolicies(peerImportParameters, routeAttrs,
505 verifyNotNull(tableTypeRegistry.getAfiSafiType(ribSupport.getTablesKey())));
507 if (optEffAtt.isEmpty()) {
508 deleteRoute(tx, ribSupport, routePath, routeBefore);
511 handleRouteTarget(ModificationType.WRITE, ribSupport, routePath, routeAfter);
512 tx.put(LogicalDatastoreType.OPERATIONAL, routePath, routeAfter);
513 CountersUtil.increment(prefixesInstalled.get(tablesKey), tablesKey);
515 final Attributes attToStore = optEffAtt.orElseThrow();
516 if (!attToStore.equals(routeAttrs)) {
517 final YangInstanceIdentifier attPath = routePath.node(ribSupport.routeAttributesIdentifier());
518 final ContainerNode finalAttribute = ribSupport.attributeToContainerNode(attPath, attToStore);
519 tx.put(LogicalDatastoreType.OPERATIONAL, attPath, finalAttribute);
523 private void addRouteTarget(final RouteTargetConstrainRoute rtc) {
524 final RouteTarget rtMembership = RouteTargetMembeshipUtil.getRT(rtc);
525 if (PeerRole.Ebgp != peerImportParameters.getFromPeerRole()) {
526 rtCache.cacheRoute(rtc);
528 rtMemberships.add(rtMembership);
531 private void deleteRouteTarget(final RIBSupport<?, ?> ribSupport, final YangInstanceIdentifier routeIdPath,
532 final NormalizedNode route) {
533 deleteRouteTarget((RouteTargetConstrainRoute) ribSupport.fromNormalizedNode(routeIdPath, route));
536 private void deleteRouteTarget(final RouteTargetConstrainRoute rtc) {
537 final RouteTarget rtMembership = RouteTargetMembeshipUtil.getRT(rtc);
538 if (PeerRole.Ebgp != peerImportParameters.getFromPeerRole()) {
539 rtCache.uncacheRoute(rtc);
541 rtMemberships.remove(rtMembership);
544 private void handleRouteTarget(final ModificationType modificationType, final RIBSupport<?, ?> ribSupport,
545 final YangInstanceIdentifier routeIdPath, final NormalizedNode route) {
546 if (RouteTargetConstrainSubsequentAddressFamily.VALUE.equals(ribSupport.getTablesKey().getSafi())) {
547 final var rtc = (RouteTargetConstrainRoute) ribSupport.fromNormalizedNode(routeIdPath, route);
548 if (ModificationType.DELETE == modificationType) {
549 deleteRouteTarget(rtc);
553 rtMembershipsUpdated = true;
557 @SuppressFBWarnings("UPM_UNCALLED_PRIVATE_METHOD")
558 private static Attributes wrapLongLivedStale(final Attributes attrs) {
560 return STALE_LLGR_ATTRIBUTES;
563 final List<Communities> oldCommunities = attrs.getCommunities();
564 final List<Communities> newCommunities;
565 if (oldCommunities != null) {
566 if (oldCommunities.contains(StaleCommunities.STALE_LLGR)) {
569 newCommunities = StaleCommunities.create(oldCommunities);
571 newCommunities = STALE_LLGR_COMMUNUTIES;
574 return new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120
575 .path.attributes.AttributesBuilder(attrs).setCommunities(newCommunities).build();
578 // XXX: this should be moved to YangInstanceIdentifier at some point
579 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
580 YangInstanceIdentifier ret = parent;
581 for (PathArgument arg : args) {
587 private YangInstanceIdentifier effectiveTablePath(final NodeIdentifierWithPredicates tableKey) {
588 return effRibTables.node(TABLES_NID).node(tableKey);
591 private static YangInstanceIdentifier routeMapPath(final RIBSupport<?, ?> ribSupport,
592 final YangInstanceIdentifier tablePath) {
593 return concat(tablePath.node(ROUTES_NID), ribSupport.relativeRoutesPath());
596 private static Optional<NormalizedNode> findRoutesMap(final RIBSupport<?, ?> ribSupport,
597 final Optional<NormalizedNode> optRoutes) {
598 return NormalizedNodes.findNode(optRoutes, ribSupport.relativeRoutesPath());
601 private static ContainerNode extractContainer(final NormalizedNode node) {
602 verify(node instanceof ContainerNode, "Expected ContainerNode, got %s", node);
603 return (ContainerNode) node;
606 private static MapNode extractMap(final Optional<? extends NormalizedNode> optNode) {
607 final NormalizedNode node = optNode.orElseThrow();
608 verify(node instanceof MapNode, "Expected MapNode, got %s", node);
609 return (MapNode) node;
612 private static boolean isLongLivedStale(final ContainerNode attributes) {
613 return NormalizedNodes.findNode(attributes, LLGR_STALE_NID).isPresent();
616 private static boolean isLongLivedStaleTable(final Optional<NormalizedNode> optTable) {
617 final Optional<NormalizedNode> optAttributes = NormalizedNodes.findNode(optTable, ATTRIBUTES_NID);
618 return optAttributes.isPresent() && isLongLivedStale(extractContainer(optAttributes.orElseThrow()));
621 private static ContainerNode effectiveAttributes(final ContainerNode attrs) {
622 final var upToDate = attrs.childByArg(UPTODATE_NID);
623 if (upToDate != null) {
624 final Object value = upToDate.body();
625 verify(value instanceof Boolean, "Expected boolean uptodate, got %s", value);
626 if ((Boolean) value) {
627 return RIBNormalizedNodes.UPTODATE_ATTRIBUTES;
630 return RIBNormalizedNodes.NOT_UPTODATE_ATTRIBUTES;