Bump upstreams
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / EffectiveRibInWriter.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.protocol.bgp.rib.impl;
9
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;
20
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;
30 import java.util.Map;
31 import java.util.Optional;
32 import java.util.Set;
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;
87
88 /**
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.
91  *
92  * <p>
93  * Inbound policy is applied as follows:
94  *
95  * <p>
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
100  *
101  * <p>
102  * This class is NOT thread-safe.
103  */
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)
116             .build();
117     private static final ChoiceNode EMPTY_ROUTES = Builders.choiceBuilder().withNodeIdentifier(ROUTES_NID).build();
118
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;
133     @GuardedBy("this")
134     private FluentFuture<? extends CommitInfo> submitted;
135     private boolean rtMembershipsUpdated;
136
137     EffectiveRibInWriter(
138             final BGPRouteEntryImportParameters peer,
139             final RIB rib,
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;
159     }
160
161     public void init() {
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);
166     }
167
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()));
171         return b.build();
172     }
173
174     @Override
175     public synchronized void onInitialData() {
176         // FIXME: update as if root was deleted
177     }
178
179     @Override
180     public synchronized void onDataTreeChanged(final List<DataTreeCandidate> changes) {
181         if (chain == null) {
182             LOG.trace("Chain closed. Ignoring Changes : {}", changes);
183             return;
184         }
185
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()) {
192                 if (tx == null) {
193                     tx = chain.newWriteOnlyTransaction();
194                 }
195                 changeDataTree(tx, rootPath, root, table);
196             }
197         }
198
199         if (tx != null) {
200             final FluentFuture<? extends CommitInfo> future = tx.commit();
201             submitted = future;
202             future.addCallback(new FutureCallback<CommitInfo>() {
203                 @Override
204                 public void onSuccess(final CommitInfo result) {
205                     LOG.trace("Successful commit");
206                 }
207
208                 @Override
209                 public void onFailure(final Throwable trw) {
210                     LOG.error("Failed commit", trw);
211                 }
212             }, MoreExecutors.directExecutor());
213         }
214
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;
220         }
221     }
222
223     @Override
224     public synchronized void close() {
225         if (reg != null) {
226             reg.close();
227             reg = null;
228         }
229         if (submitted != null) {
230             try {
231                 submitted.get();
232             } catch (final InterruptedException | ExecutionException throwable) {
233                 LOG.error("Write routes failed", throwable);
234             }
235         }
236         if (chain != null) {
237             chain.close();
238             chain = null;
239         }
240         prefixesReceived.values().forEach(LongAdder::reset);
241         prefixesInstalled.values().forEach(LongAdder::reset);
242     }
243
244     @Override
245     public long getPrefixedReceivedCount(final TablesKey tablesKey) {
246         final LongAdder counter = prefixesReceived.get(tablesKey);
247         if (counter == null) {
248             return 0;
249         }
250         return counter.longValue();
251     }
252
253     @Override
254     public Set<TablesKey> getTableKeys() {
255         return ImmutableSet.copyOf(prefixesReceived.keySet());
256     }
257
258     @Override
259     public boolean isSupported(final TablesKey tablesKey) {
260         return prefixesReceived.containsKey(tablesKey);
261     }
262
263     @Override
264     public long getPrefixedInstalledCount(final TablesKey tablesKey) {
265         final LongAdder counter = prefixesInstalled.get(tablesKey);
266         if (counter == null) {
267             return 0;
268         }
269         return counter.longValue();
270     }
271
272     @Override
273     public long getTotalPrefixesInstalled() {
274         return prefixesInstalled.values().stream().mapToLong(LongAdder::longValue).sum();
275     }
276
277     @Holding("this")
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(),
282             rootPath);
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);
287             return;
288         }
289
290         final YangInstanceIdentifier effectiveTablePath = effectiveTablePath(tableKey);
291         final ModificationType modificationType = root.modificationType();
292         LOG.debug("Effective table {} modification type {}", effectiveTablePath, modificationType);
293         switch (modificationType) {
294             case DISAPPEARED:
295             case DELETE:
296                 deleteTable(tx, ribContext, effectiveTablePath, table);
297                 break;
298             case APPEARED:
299             case WRITE:
300                 writeTable(tx, ribContext, effectiveTablePath, table);
301                 break;
302             case SUBTREE_MODIFIED:
303                 modifyTable(tx, ribContext, effectiveTablePath, table);
304                 break;
305             case UNMODIFIED:
306                 LOG.info("Ignoring spurious notification on {} data {}", rootPath, table);
307                 break;
308             default:
309                 LOG.warn("Ignoring unhandled root {}", table);
310                 break;
311         }
312     }
313
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);
319     }
320
321     private void modifyTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
322             final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
323         LOG.debug("Modify Effective Table {}", effectiveTablePath);
324
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",
329                     effectiveTablePath);
330             writeTable(tx, ribContext, effectiveTablePath, table);
331             return;
332         }
333
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)));
341             } else {
342                 tx.delete(LogicalDatastoreType.OPERATIONAL, effAttrsPath);
343             }
344         }
345
346         final var modifiedRoutes = table.modifiedChild(ROUTES_NID);
347         if (modifiedRoutes != null) {
348             final RIBSupport<?, ?> ribSupport = ribContext.getRibSupport();
349             switch (modifiedRoutes.modificationType()) {
350                 case APPEARED:
351                 case WRITE:
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(),
356                         longLivedStale);
357                     break;
358                 case DELETE:
359                 case DISAPPEARED:
360                     deleteRoutesBefore(tx, ribSupport, effectiveTablePath, modifiedRoutes);
361                     tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ROUTES_NID));
362                     break;
363                 case SUBTREE_MODIFIED:
364                     for (DataTreeCandidateNode modifiedRoute : ribSupport.changedRoutes(modifiedRoutes)) {
365                         processRoute(tx, ribSupport, effectiveTablePath, modifiedRoute, longLivedStale);
366                     }
367                     break;
368                 case UNMODIFIED:
369                     // No-op
370                     return;
371                 default:
372                     LOG.warn("Ignoring modified routes {}", modifiedRoutes);
373                     break;
374             }
375         }
376     }
377
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());
382
383         final var node = table.dataAfter();
384         if (node != null) {
385             verify(node instanceof MapEntryNode, "Expected MapEntryNode, got %s", node);
386             final MapEntryNode tableAfter = (MapEntryNode) node;
387             ribContext.createEmptyTableStructure(tx, effectiveTablePath);
388
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));
396             } else {
397                 longLivedStale = false;
398             }
399
400             writeRoutesAfter(tx, ribContext.getRibSupport(), effectiveTablePath,
401                 NormalizedNodes.findNode(tableAfter, ROUTES_NID), longLivedStale);
402         }
403     }
404
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());
412         }
413     }
414
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());
421         }
422     }
423
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);
433             }
434         }
435     }
436
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);
443             }
444             rtMembershipsUpdated = true;
445         }
446
447         final TablesKey tablesKey = ribSupport.getTablesKey();
448         CountersUtil.add(prefixesInstalled.get(tablesKey), tablesKey, -deletedRoutes.size());
449     }
450
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()) {
456             case DELETE:
457             case DISAPPEARED:
458                 deleteRoute(tx, ribSupport, routePath, route.dataBefore());
459                 break;
460             case UNMODIFIED:
461                 // No-op
462                 break;
463             case APPEARED:
464             case SUBTREE_MODIFIED:
465             case WRITE:
466                 writeRoute(tx, ribSupport, routePath, route.dataBefore(), route.getDataAfter(), longLivedStale);
467                 break;
468             default:
469                 LOG.warn("Ignoring unhandled route {}", route);
470                 break;
471         }
472     }
473
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);
481     }
482
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);
500                 return;
501             }
502             optEffAtt = Optional.of(wrapLongLivedStale(routeAttrs));
503         } else {
504             optEffAtt = ribPolicies.applyImportPolicies(peerImportParameters, routeAttrs,
505                 verifyNotNull(tableTypeRegistry.getAfiSafiType(ribSupport.getTablesKey())));
506         }
507         if (optEffAtt.isEmpty()) {
508             deleteRoute(tx, ribSupport, routePath, routeBefore);
509             return;
510         }
511         handleRouteTarget(ModificationType.WRITE, ribSupport, routePath, routeAfter);
512         tx.put(LogicalDatastoreType.OPERATIONAL, routePath, routeAfter);
513         CountersUtil.increment(prefixesInstalled.get(tablesKey), tablesKey);
514
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);
520         }
521     }
522
523     private void addRouteTarget(final RouteTargetConstrainRoute rtc) {
524         final RouteTarget rtMembership = RouteTargetMembeshipUtil.getRT(rtc);
525         if (PeerRole.Ebgp != peerImportParameters.getFromPeerRole()) {
526             rtCache.cacheRoute(rtc);
527         }
528         rtMemberships.add(rtMembership);
529     }
530
531     private void deleteRouteTarget(final RIBSupport<?, ?> ribSupport, final YangInstanceIdentifier routeIdPath,
532             final NormalizedNode route) {
533         deleteRouteTarget((RouteTargetConstrainRoute) ribSupport.fromNormalizedNode(routeIdPath, route));
534     }
535
536     private void deleteRouteTarget(final RouteTargetConstrainRoute rtc) {
537         final RouteTarget rtMembership = RouteTargetMembeshipUtil.getRT(rtc);
538         if (PeerRole.Ebgp != peerImportParameters.getFromPeerRole()) {
539             rtCache.uncacheRoute(rtc);
540         }
541         rtMemberships.remove(rtMembership);
542     }
543
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);
550             } else {
551                 addRouteTarget(rtc);
552             }
553             rtMembershipsUpdated = true;
554         }
555     }
556
557     @SuppressFBWarnings("UPM_UNCALLED_PRIVATE_METHOD")
558     private static Attributes wrapLongLivedStale(final Attributes attrs) {
559         if (attrs == null) {
560             return STALE_LLGR_ATTRIBUTES;
561         }
562
563         final List<Communities> oldCommunities = attrs.getCommunities();
564         final List<Communities> newCommunities;
565         if (oldCommunities != null) {
566             if (oldCommunities.contains(StaleCommunities.STALE_LLGR)) {
567                 return attrs;
568             }
569             newCommunities = StaleCommunities.create(oldCommunities);
570         } else {
571             newCommunities = STALE_LLGR_COMMUNUTIES;
572         }
573
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();
576     }
577
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) {
582             ret = ret.node(arg);
583         }
584         return ret;
585     }
586
587     private YangInstanceIdentifier effectiveTablePath(final NodeIdentifierWithPredicates tableKey) {
588         return effRibTables.node(TABLES_NID).node(tableKey);
589     }
590
591     private static YangInstanceIdentifier routeMapPath(final RIBSupport<?, ?> ribSupport,
592             final YangInstanceIdentifier tablePath) {
593         return concat(tablePath.node(ROUTES_NID), ribSupport.relativeRoutesPath());
594     }
595
596     private static Optional<NormalizedNode> findRoutesMap(final RIBSupport<?, ?> ribSupport,
597             final Optional<NormalizedNode> optRoutes) {
598         return NormalizedNodes.findNode(optRoutes, ribSupport.relativeRoutesPath());
599     }
600
601     private static ContainerNode extractContainer(final NormalizedNode node) {
602         verify(node instanceof ContainerNode, "Expected ContainerNode, got %s", node);
603         return (ContainerNode) node;
604     }
605
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;
610     }
611
612     private static boolean isLongLivedStale(final ContainerNode attributes) {
613         return NormalizedNodes.findNode(attributes, LLGR_STALE_NID).isPresent();
614     }
615
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()));
619     }
620
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;
628             }
629         }
630         return RIBNormalizedNodes.NOT_UPTODATE_ATTRIBUTES;
631     }
632 }