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.spi.node.ImmutableNodes;
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 = ImmutableNodes.newChoiceBuilder()
118 .withNodeIdentifier(ROUTES_NID)
121 private final RIBSupportContextRegistry registry;
122 private final YangInstanceIdentifier peerIId;
123 private final YangInstanceIdentifier effRibTables;
124 private final DataTreeChangeExtension service;
125 private final List<RouteTarget> rtMemberships;
126 private final RibOutRefresh vpnTableRefresher;
127 private final ClientRouteTargetContrainCache rtCache;
128 private Registration reg;
129 private DOMTransactionChain chain;
130 private final Map<TablesKey, LongAdder> prefixesReceived;
131 private final Map<TablesKey, LongAdder> prefixesInstalled;
132 private final BGPRibRoutingPolicy ribPolicies;
133 private final BGPRouteEntryImportParameters peerImportParameters;
134 private final BGPTableTypeRegistryConsumer tableTypeRegistry;
136 private FluentFuture<? extends CommitInfo> submitted;
137 private boolean rtMembershipsUpdated;
139 EffectiveRibInWriter(
140 final BGPRouteEntryImportParameters peer,
142 final DOMTransactionChain chain,
143 final YangInstanceIdentifier peerIId,
144 final Set<TablesKey> tables,
145 final BGPTableTypeRegistryConsumer tableTypeRegistry,
146 final List<RouteTarget> rtMemberships,
147 final ClientRouteTargetContrainCache rtCache) {
148 registry = requireNonNull(rib.getRibSupportContext());
149 this.chain = requireNonNull(chain);
150 this.peerIId = requireNonNull(peerIId);
151 effRibTables = this.peerIId.node(EFFRIBIN_NID);
152 prefixesInstalled = buildPrefixesTables(tables);
153 prefixesReceived = buildPrefixesTables(tables);
154 ribPolicies = requireNonNull(rib.getRibPolicies());
155 service = requireNonNull(rib.getService());
156 this.tableTypeRegistry = requireNonNull(tableTypeRegistry);
157 peerImportParameters = peer;
158 this.rtMemberships = rtMemberships;
159 this.rtCache = rtCache;
160 vpnTableRefresher = rib;
164 final DOMDataTreeIdentifier treeId = DOMDataTreeIdentifier.of(LogicalDatastoreType.OPERATIONAL,
165 peerIId.node(ADJRIBIN_NID).node(TABLES_NID));
166 LOG.debug("Registered Effective RIB on {}", peerIId);
167 reg = requireNonNull(service).registerTreeChangeListener(treeId, this);
170 private static Map<TablesKey, LongAdder> buildPrefixesTables(final Set<TablesKey> tables) {
171 final ImmutableMap.Builder<TablesKey, LongAdder> b = ImmutableMap.builder();
172 tables.forEach(table -> b.put(table, new LongAdder()));
177 public synchronized void onInitialData() {
178 // FIXME: update as if root was deleted
182 public synchronized void onDataTreeChanged(final List<DataTreeCandidate> changes) {
184 LOG.trace("Chain closed. Ignoring Changes : {}", changes);
188 LOG.trace("Data changed called to effective RIB. Change : {}", changes);
189 DOMDataTreeWriteTransaction tx = null;
190 for (final DataTreeCandidate tc : changes) {
191 final YangInstanceIdentifier rootPath = tc.getRootPath();
192 final DataTreeCandidateNode root = tc.getRootNode();
193 for (final DataTreeCandidateNode table : root.childNodes()) {
195 tx = chain.newWriteOnlyTransaction();
197 changeDataTree(tx, rootPath, root, table);
202 final FluentFuture<? extends CommitInfo> future = tx.commit();
204 future.addCallback(new FutureCallback<CommitInfo>() {
206 public void onSuccess(final CommitInfo result) {
207 LOG.trace("Successful commit");
211 public void onFailure(final Throwable trw) {
212 LOG.error("Failed commit", trw);
214 }, MoreExecutors.directExecutor());
217 //Refresh VPN Table if RT Memberships were updated
218 if (rtMembershipsUpdated) {
219 vpnTableRefresher.refreshTable(IVP4_VPN_TABLE_KEY, peerImportParameters.getFromPeerId());
220 vpnTableRefresher.refreshTable(IVP6_VPN_TABLE_KEY, peerImportParameters.getFromPeerId());
221 rtMembershipsUpdated = false;
226 public synchronized void close() {
231 if (submitted != null) {
234 } catch (final InterruptedException | ExecutionException throwable) {
235 LOG.error("Write routes failed", throwable);
242 prefixesReceived.values().forEach(LongAdder::reset);
243 prefixesInstalled.values().forEach(LongAdder::reset);
247 public long getPrefixedReceivedCount(final TablesKey tablesKey) {
248 final LongAdder counter = prefixesReceived.get(tablesKey);
249 if (counter == null) {
252 return counter.longValue();
256 public Set<TablesKey> getTableKeys() {
257 return ImmutableSet.copyOf(prefixesReceived.keySet());
261 public boolean isSupported(final TablesKey tablesKey) {
262 return prefixesReceived.containsKey(tablesKey);
266 public long getPrefixedInstalledCount(final TablesKey tablesKey) {
267 final LongAdder counter = prefixesInstalled.get(tablesKey);
268 if (counter == null) {
271 return counter.longValue();
275 public long getTotalPrefixesInstalled() {
276 return prefixesInstalled.values().stream().mapToLong(LongAdder::longValue).sum();
280 private void changeDataTree(final DOMDataTreeWriteTransaction tx, final YangInstanceIdentifier rootPath,
281 final DataTreeCandidateNode root, final DataTreeCandidateNode table) {
282 final PathArgument lastArg = table.name();
283 verify(lastArg instanceof NodeIdentifierWithPredicates, "Unexpected type %s in path %s", lastArg.getClass(),
285 final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
286 final RIBSupportContext ribContext = registry.getRIBSupportContext(tableKey);
287 if (ribContext == null) {
288 LOG.warn("Table {} is not supported, ignoring event", tableKey);
292 final YangInstanceIdentifier effectiveTablePath = effectiveTablePath(tableKey);
293 final ModificationType modificationType = root.modificationType();
294 LOG.debug("Effective table {} modification type {}", effectiveTablePath, modificationType);
295 switch (modificationType) {
298 deleteTable(tx, ribContext, effectiveTablePath, table);
302 writeTable(tx, ribContext, effectiveTablePath, table);
304 case SUBTREE_MODIFIED:
305 modifyTable(tx, ribContext, effectiveTablePath, table);
308 LOG.info("Ignoring spurious notification on {} data {}", rootPath, table);
311 LOG.warn("Ignoring unhandled root {}", table);
316 private void deleteTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
317 final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
318 LOG.debug("Delete Effective Table {}", effectiveTablePath);
319 onDeleteTable(ribContext.getRibSupport(), effectiveTablePath, table.dataBefore());
320 tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath);
323 private void modifyTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
324 final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
325 LOG.debug("Modify Effective Table {}", effectiveTablePath);
327 final boolean wasLongLivedStale = isLongLivedStaleTable(table.findDataBefore());
328 final boolean longLivedStale = isLongLivedStaleTable(table.findDataAfter());
329 if (wasLongLivedStale != longLivedStale) {
330 LOG.debug("LLGR_STALE flag flipped {}, overwriting table {}", longLivedStale ? "ON" : "OFF",
332 writeTable(tx, ribContext, effectiveTablePath, table);
336 final var modifiedAttrs = table.modifiedChild(ATTRIBUTES_NID);
337 if (modifiedAttrs != null) {
338 final YangInstanceIdentifier effAttrsPath = effectiveTablePath.node(ATTRIBUTES_NID);
339 final var attrsAfter = modifiedAttrs.dataAfter();
340 if (attrsAfter != null) {
341 tx.put(LogicalDatastoreType.OPERATIONAL, effAttrsPath,
342 effectiveAttributes(extractContainer(attrsAfter)));
344 tx.delete(LogicalDatastoreType.OPERATIONAL, effAttrsPath);
348 final var modifiedRoutes = table.modifiedChild(ROUTES_NID);
349 if (modifiedRoutes != null) {
350 final RIBSupport<?, ?> ribSupport = ribContext.getRibSupport();
351 switch (modifiedRoutes.modificationType()) {
354 deleteRoutesBefore(tx, ribSupport, effectiveTablePath, modifiedRoutes);
355 // XXX: YANG Tools seems to have an issue stacking DELETE with child WRITE
356 tx.put(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ROUTES_NID), EMPTY_ROUTES);
357 writeRoutesAfter(tx, ribSupport, effectiveTablePath, modifiedRoutes.findDataAfter(),
362 deleteRoutesBefore(tx, ribSupport, effectiveTablePath, modifiedRoutes);
363 tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ROUTES_NID));
365 case SUBTREE_MODIFIED:
366 for (DataTreeCandidateNode modifiedRoute : ribSupport.changedRoutes(modifiedRoutes)) {
367 processRoute(tx, ribSupport, effectiveTablePath, modifiedRoute, longLivedStale);
374 LOG.warn("Ignoring modified routes {}", modifiedRoutes);
380 private void writeTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
381 final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
382 LOG.debug("Write Effective Table {}", effectiveTablePath);
383 onDeleteTable(ribContext.getRibSupport(), effectiveTablePath, table.dataBefore());
385 final var node = table.dataAfter();
387 verify(node instanceof MapEntryNode, "Expected MapEntryNode, got %s", node);
388 final MapEntryNode tableAfter = (MapEntryNode) node;
389 ribContext.createEmptyTableStructure(tx, effectiveTablePath);
391 final DataContainerChild maybeAttrsAfter = tableAfter.childByArg(ATTRIBUTES_NID);
392 final boolean longLivedStale;
393 if (maybeAttrsAfter != null) {
394 final ContainerNode attrsAfter = extractContainer(maybeAttrsAfter);
395 longLivedStale = isLongLivedStale(attrsAfter);
396 tx.put(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ATTRIBUTES_NID),
397 effectiveAttributes(attrsAfter));
399 longLivedStale = false;
402 writeRoutesAfter(tx, ribContext.getRibSupport(), effectiveTablePath,
403 NormalizedNodes.findNode(tableAfter, ROUTES_NID), longLivedStale);
407 // Performs house-keeping when the contents of a table is deleted
408 private void onDeleteTable(final RIBSupport<?, ?> ribSupport, final YangInstanceIdentifier effectiveTablePath,
409 final @Nullable NormalizedNode tableBefore) {
410 // Routes are special in that we need to process the to keep our counters accurate
411 final var maybeRoutesBefore = findRoutesMap(ribSupport, NormalizedNodes.findNode(tableBefore, ROUTES_NID));
412 if (maybeRoutesBefore.isPresent()) {
413 onRoutesDeleted(ribSupport, effectiveTablePath, extractMap(maybeRoutesBefore).body());
417 private void deleteRoutesBefore(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?> ribSupport,
418 final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode modifiedRoutes) {
419 final Optional<NormalizedNode> maybeRoutesBefore =
420 NormalizedNodes.findNode(modifiedRoutes.dataBefore(), ribSupport.relativeRoutesPath());
421 if (maybeRoutesBefore.isPresent()) {
422 onRoutesDeleted(ribSupport, effectiveTablePath, extractMap(maybeRoutesBefore).body());
426 private void writeRoutesAfter(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?> ribSupport,
427 final YangInstanceIdentifier effectiveTablePath, final Optional<NormalizedNode> routesAfter,
428 final boolean longLivedStale) {
429 final Optional<NormalizedNode> maybeRoutesAfter = NormalizedNodes.findNode(routesAfter,
430 ribSupport.relativeRoutesPath());
431 if (maybeRoutesAfter.isPresent()) {
432 final YangInstanceIdentifier routesPath = routeMapPath(ribSupport, effectiveTablePath);
433 for (MapEntryNode routeAfter : extractMap(maybeRoutesAfter).body()) {
434 writeRoute(tx, ribSupport, routesPath.node(routeAfter.name()), null, routeAfter, longLivedStale);
439 private void onRoutesDeleted(final RIBSupport<?, ?> ribSupport, final YangInstanceIdentifier effectiveTablePath,
440 final Collection<MapEntryNode> deletedRoutes) {
441 if (RouteTargetConstrainSubsequentAddressFamily.VALUE.equals(ribSupport.getTablesKey().getSafi())) {
442 final YangInstanceIdentifier routesPath = routeMapPath(ribSupport, effectiveTablePath);
443 for (final MapEntryNode routeBefore : deletedRoutes) {
444 deleteRouteTarget(ribSupport, routesPath.node(routeBefore.name()), routeBefore);
446 rtMembershipsUpdated = true;
449 final TablesKey tablesKey = ribSupport.getTablesKey();
450 CountersUtil.add(prefixesInstalled.get(tablesKey), tablesKey, -deletedRoutes.size());
453 private void processRoute(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?> ribSupport,
454 final YangInstanceIdentifier routesPath, final DataTreeCandidateNode route, final boolean longLivedStale) {
455 LOG.debug("Process route {}", route.name());
456 final YangInstanceIdentifier routePath = ribSupport.routePath(routesPath, route.name());
457 switch (route.modificationType()) {
460 deleteRoute(tx, ribSupport, routePath, route.dataBefore());
466 case SUBTREE_MODIFIED:
468 writeRoute(tx, ribSupport, routePath, route.dataBefore(), route.getDataAfter(), longLivedStale);
471 LOG.warn("Ignoring unhandled route {}", route);
476 private void deleteRoute(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?> ribSupport,
477 final YangInstanceIdentifier routeIdPath, final NormalizedNode route) {
478 handleRouteTarget(ModificationType.DELETE, ribSupport, routeIdPath, route);
479 tx.delete(LogicalDatastoreType.OPERATIONAL, routeIdPath);
480 LOG.debug("Route deleted. routeId={}", routeIdPath);
481 final TablesKey tablesKey = ribSupport.getTablesKey();
482 CountersUtil.decrement(prefixesInstalled.get(tablesKey), tablesKey);
485 private void writeRoute(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?> ribSupport,
486 final YangInstanceIdentifier routePath, final @Nullable NormalizedNode routeBefore,
487 final @NonNull NormalizedNode routeAfter, final boolean longLivedStale) {
488 final TablesKey tablesKey = ribSupport.getTablesKey();
489 CountersUtil.increment(prefixesReceived.get(tablesKey), tablesKey);
490 // Lookup per-table attributes from RIBSupport
491 final ContainerNode advertisedAttrs = (ContainerNode) NormalizedNodes.findNode(routeAfter,
492 ribSupport.routeAttributesIdentifier()).orElse(null);
493 final Attributes routeAttrs = ribSupport.attributeFromContainerNode(advertisedAttrs);
494 final Optional<Attributes> optEffAtt;
495 // In case we want to add LLGR_STALE we do not process route through policies since it may be
496 // considered as received with LLGR_STALE from peer which is not true.
497 if (longLivedStale) {
498 // LLGR procedures are in effect. If the route is tagged with NO_LLGR, it needs to be removed.
499 final List<Communities> effCommunities = routeAttrs.getCommunities();
500 if (effCommunities != null && effCommunities.contains(CommunityUtil.NO_LLGR)) {
501 deleteRoute(tx, ribSupport, routePath, routeBefore);
504 optEffAtt = Optional.of(wrapLongLivedStale(routeAttrs));
506 optEffAtt = ribPolicies.applyImportPolicies(peerImportParameters, routeAttrs,
507 verifyNotNull(tableTypeRegistry.getAfiSafiType(ribSupport.getTablesKey())));
509 if (optEffAtt.isEmpty()) {
510 deleteRoute(tx, ribSupport, routePath, routeBefore);
513 handleRouteTarget(ModificationType.WRITE, ribSupport, routePath, routeAfter);
514 tx.put(LogicalDatastoreType.OPERATIONAL, routePath, routeAfter);
515 CountersUtil.increment(prefixesInstalled.get(tablesKey), tablesKey);
517 final Attributes attToStore = optEffAtt.orElseThrow();
518 if (!attToStore.equals(routeAttrs)) {
519 final YangInstanceIdentifier attPath = routePath.node(ribSupport.routeAttributesIdentifier());
520 final ContainerNode finalAttribute = ribSupport.attributeToContainerNode(attPath, attToStore);
521 tx.put(LogicalDatastoreType.OPERATIONAL, attPath, finalAttribute);
525 private void addRouteTarget(final RouteTargetConstrainRoute rtc) {
526 final RouteTarget rtMembership = RouteTargetMembeshipUtil.getRT(rtc);
527 if (PeerRole.Ebgp != peerImportParameters.getFromPeerRole()) {
528 rtCache.cacheRoute(rtc);
530 rtMemberships.add(rtMembership);
533 private void deleteRouteTarget(final RIBSupport<?, ?> ribSupport, final YangInstanceIdentifier routeIdPath,
534 final NormalizedNode route) {
535 deleteRouteTarget((RouteTargetConstrainRoute) ribSupport.fromNormalizedNode(routeIdPath, route));
538 private void deleteRouteTarget(final RouteTargetConstrainRoute rtc) {
539 final RouteTarget rtMembership = RouteTargetMembeshipUtil.getRT(rtc);
540 if (PeerRole.Ebgp != peerImportParameters.getFromPeerRole()) {
541 rtCache.uncacheRoute(rtc);
543 rtMemberships.remove(rtMembership);
546 private void handleRouteTarget(final ModificationType modificationType, final RIBSupport<?, ?> ribSupport,
547 final YangInstanceIdentifier routeIdPath, final NormalizedNode route) {
548 if (RouteTargetConstrainSubsequentAddressFamily.VALUE.equals(ribSupport.getTablesKey().getSafi())) {
549 final var rtc = (RouteTargetConstrainRoute) ribSupport.fromNormalizedNode(routeIdPath, route);
550 if (ModificationType.DELETE == modificationType) {
551 deleteRouteTarget(rtc);
555 rtMembershipsUpdated = true;
559 @SuppressFBWarnings("UPM_UNCALLED_PRIVATE_METHOD")
560 private static Attributes wrapLongLivedStale(final Attributes attrs) {
562 return STALE_LLGR_ATTRIBUTES;
565 final List<Communities> oldCommunities = attrs.getCommunities();
566 final List<Communities> newCommunities;
567 if (oldCommunities != null) {
568 if (oldCommunities.contains(StaleCommunities.STALE_LLGR)) {
571 newCommunities = StaleCommunities.create(oldCommunities);
573 newCommunities = STALE_LLGR_COMMUNUTIES;
576 return new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120
577 .path.attributes.AttributesBuilder(attrs).setCommunities(newCommunities).build();
580 // XXX: this should be moved to YangInstanceIdentifier at some point
581 private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
582 YangInstanceIdentifier ret = parent;
583 for (PathArgument arg : args) {
589 private YangInstanceIdentifier effectiveTablePath(final NodeIdentifierWithPredicates tableKey) {
590 return effRibTables.node(TABLES_NID).node(tableKey);
593 private static YangInstanceIdentifier routeMapPath(final RIBSupport<?, ?> ribSupport,
594 final YangInstanceIdentifier tablePath) {
595 return concat(tablePath.node(ROUTES_NID), ribSupport.relativeRoutesPath());
598 private static Optional<NormalizedNode> findRoutesMap(final RIBSupport<?, ?> ribSupport,
599 final Optional<NormalizedNode> optRoutes) {
600 return NormalizedNodes.findNode(optRoutes, ribSupport.relativeRoutesPath());
603 private static ContainerNode extractContainer(final NormalizedNode node) {
604 verify(node instanceof ContainerNode, "Expected ContainerNode, got %s", node);
605 return (ContainerNode) node;
608 private static MapNode extractMap(final Optional<? extends NormalizedNode> optNode) {
609 final NormalizedNode node = optNode.orElseThrow();
610 verify(node instanceof MapNode, "Expected MapNode, got %s", node);
611 return (MapNode) node;
614 private static boolean isLongLivedStale(final ContainerNode attributes) {
615 return NormalizedNodes.findNode(attributes, 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.orElseThrow()));
623 private static ContainerNode effectiveAttributes(final ContainerNode attrs) {
624 final var upToDate = attrs.childByArg(UPTODATE_NID);
625 if (upToDate != null) {
626 final Object value = upToDate.body();
627 verify(value instanceof Boolean, "Expected boolean uptodate, got %s", value);
628 if ((Boolean) value) {
629 return RIBNormalizedNodes.UPTODATE_ATTRIBUTES;
632 return RIBNormalizedNodes.NOT_UPTODATE_ATTRIBUTES;