Migrate bgp-rib-impl use of Builders
[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.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;
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 = ImmutableNodes.newChoiceBuilder()
118         .withNodeIdentifier(ROUTES_NID)
119         .build();
120
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;
135     @GuardedBy("this")
136     private FluentFuture<? extends CommitInfo> submitted;
137     private boolean rtMembershipsUpdated;
138
139     EffectiveRibInWriter(
140             final BGPRouteEntryImportParameters peer,
141             final RIB rib,
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;
161     }
162
163     public void init() {
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);
168     }
169
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()));
173         return b.build();
174     }
175
176     @Override
177     public synchronized void onInitialData() {
178         // FIXME: update as if root was deleted
179     }
180
181     @Override
182     public synchronized void onDataTreeChanged(final List<DataTreeCandidate> changes) {
183         if (chain == null) {
184             LOG.trace("Chain closed. Ignoring Changes : {}", changes);
185             return;
186         }
187
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()) {
194                 if (tx == null) {
195                     tx = chain.newWriteOnlyTransaction();
196                 }
197                 changeDataTree(tx, rootPath, root, table);
198             }
199         }
200
201         if (tx != null) {
202             final FluentFuture<? extends CommitInfo> future = tx.commit();
203             submitted = future;
204             future.addCallback(new FutureCallback<CommitInfo>() {
205                 @Override
206                 public void onSuccess(final CommitInfo result) {
207                     LOG.trace("Successful commit");
208                 }
209
210                 @Override
211                 public void onFailure(final Throwable trw) {
212                     LOG.error("Failed commit", trw);
213                 }
214             }, MoreExecutors.directExecutor());
215         }
216
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;
222         }
223     }
224
225     @Override
226     public synchronized void close() {
227         if (reg != null) {
228             reg.close();
229             reg = null;
230         }
231         if (submitted != null) {
232             try {
233                 submitted.get();
234             } catch (final InterruptedException | ExecutionException throwable) {
235                 LOG.error("Write routes failed", throwable);
236             }
237         }
238         if (chain != null) {
239             chain.close();
240             chain = null;
241         }
242         prefixesReceived.values().forEach(LongAdder::reset);
243         prefixesInstalled.values().forEach(LongAdder::reset);
244     }
245
246     @Override
247     public long getPrefixedReceivedCount(final TablesKey tablesKey) {
248         final LongAdder counter = prefixesReceived.get(tablesKey);
249         if (counter == null) {
250             return 0;
251         }
252         return counter.longValue();
253     }
254
255     @Override
256     public Set<TablesKey> getTableKeys() {
257         return ImmutableSet.copyOf(prefixesReceived.keySet());
258     }
259
260     @Override
261     public boolean isSupported(final TablesKey tablesKey) {
262         return prefixesReceived.containsKey(tablesKey);
263     }
264
265     @Override
266     public long getPrefixedInstalledCount(final TablesKey tablesKey) {
267         final LongAdder counter = prefixesInstalled.get(tablesKey);
268         if (counter == null) {
269             return 0;
270         }
271         return counter.longValue();
272     }
273
274     @Override
275     public long getTotalPrefixesInstalled() {
276         return prefixesInstalled.values().stream().mapToLong(LongAdder::longValue).sum();
277     }
278
279     @Holding("this")
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(),
284             rootPath);
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);
289             return;
290         }
291
292         final YangInstanceIdentifier effectiveTablePath = effectiveTablePath(tableKey);
293         final ModificationType modificationType = root.modificationType();
294         LOG.debug("Effective table {} modification type {}", effectiveTablePath, modificationType);
295         switch (modificationType) {
296             case DISAPPEARED:
297             case DELETE:
298                 deleteTable(tx, ribContext, effectiveTablePath, table);
299                 break;
300             case APPEARED:
301             case WRITE:
302                 writeTable(tx, ribContext, effectiveTablePath, table);
303                 break;
304             case SUBTREE_MODIFIED:
305                 modifyTable(tx, ribContext, effectiveTablePath, table);
306                 break;
307             case UNMODIFIED:
308                 LOG.info("Ignoring spurious notification on {} data {}", rootPath, table);
309                 break;
310             default:
311                 LOG.warn("Ignoring unhandled root {}", table);
312                 break;
313         }
314     }
315
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);
321     }
322
323     private void modifyTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
324             final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
325         LOG.debug("Modify Effective Table {}", effectiveTablePath);
326
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",
331                     effectiveTablePath);
332             writeTable(tx, ribContext, effectiveTablePath, table);
333             return;
334         }
335
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)));
343             } else {
344                 tx.delete(LogicalDatastoreType.OPERATIONAL, effAttrsPath);
345             }
346         }
347
348         final var modifiedRoutes = table.modifiedChild(ROUTES_NID);
349         if (modifiedRoutes != null) {
350             final RIBSupport<?, ?> ribSupport = ribContext.getRibSupport();
351             switch (modifiedRoutes.modificationType()) {
352                 case APPEARED:
353                 case WRITE:
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(),
358                         longLivedStale);
359                     break;
360                 case DELETE:
361                 case DISAPPEARED:
362                     deleteRoutesBefore(tx, ribSupport, effectiveTablePath, modifiedRoutes);
363                     tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ROUTES_NID));
364                     break;
365                 case SUBTREE_MODIFIED:
366                     for (DataTreeCandidateNode modifiedRoute : ribSupport.changedRoutes(modifiedRoutes)) {
367                         processRoute(tx, ribSupport, effectiveTablePath, modifiedRoute, longLivedStale);
368                     }
369                     break;
370                 case UNMODIFIED:
371                     // No-op
372                     return;
373                 default:
374                     LOG.warn("Ignoring modified routes {}", modifiedRoutes);
375                     break;
376             }
377         }
378     }
379
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());
384
385         final var node = table.dataAfter();
386         if (node != null) {
387             verify(node instanceof MapEntryNode, "Expected MapEntryNode, got %s", node);
388             final MapEntryNode tableAfter = (MapEntryNode) node;
389             ribContext.createEmptyTableStructure(tx, effectiveTablePath);
390
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));
398             } else {
399                 longLivedStale = false;
400             }
401
402             writeRoutesAfter(tx, ribContext.getRibSupport(), effectiveTablePath,
403                 NormalizedNodes.findNode(tableAfter, ROUTES_NID), longLivedStale);
404         }
405     }
406
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());
414         }
415     }
416
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());
423         }
424     }
425
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);
435             }
436         }
437     }
438
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);
445             }
446             rtMembershipsUpdated = true;
447         }
448
449         final TablesKey tablesKey = ribSupport.getTablesKey();
450         CountersUtil.add(prefixesInstalled.get(tablesKey), tablesKey, -deletedRoutes.size());
451     }
452
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()) {
458             case DELETE:
459             case DISAPPEARED:
460                 deleteRoute(tx, ribSupport, routePath, route.dataBefore());
461                 break;
462             case UNMODIFIED:
463                 // No-op
464                 break;
465             case APPEARED:
466             case SUBTREE_MODIFIED:
467             case WRITE:
468                 writeRoute(tx, ribSupport, routePath, route.dataBefore(), route.getDataAfter(), longLivedStale);
469                 break;
470             default:
471                 LOG.warn("Ignoring unhandled route {}", route);
472                 break;
473         }
474     }
475
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);
483     }
484
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);
502                 return;
503             }
504             optEffAtt = Optional.of(wrapLongLivedStale(routeAttrs));
505         } else {
506             optEffAtt = ribPolicies.applyImportPolicies(peerImportParameters, routeAttrs,
507                 verifyNotNull(tableTypeRegistry.getAfiSafiType(ribSupport.getTablesKey())));
508         }
509         if (optEffAtt.isEmpty()) {
510             deleteRoute(tx, ribSupport, routePath, routeBefore);
511             return;
512         }
513         handleRouteTarget(ModificationType.WRITE, ribSupport, routePath, routeAfter);
514         tx.put(LogicalDatastoreType.OPERATIONAL, routePath, routeAfter);
515         CountersUtil.increment(prefixesInstalled.get(tablesKey), tablesKey);
516
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);
522         }
523     }
524
525     private void addRouteTarget(final RouteTargetConstrainRoute rtc) {
526         final RouteTarget rtMembership = RouteTargetMembeshipUtil.getRT(rtc);
527         if (PeerRole.Ebgp != peerImportParameters.getFromPeerRole()) {
528             rtCache.cacheRoute(rtc);
529         }
530         rtMemberships.add(rtMembership);
531     }
532
533     private void deleteRouteTarget(final RIBSupport<?, ?> ribSupport, final YangInstanceIdentifier routeIdPath,
534             final NormalizedNode route) {
535         deleteRouteTarget((RouteTargetConstrainRoute) ribSupport.fromNormalizedNode(routeIdPath, route));
536     }
537
538     private void deleteRouteTarget(final RouteTargetConstrainRoute rtc) {
539         final RouteTarget rtMembership = RouteTargetMembeshipUtil.getRT(rtc);
540         if (PeerRole.Ebgp != peerImportParameters.getFromPeerRole()) {
541             rtCache.uncacheRoute(rtc);
542         }
543         rtMemberships.remove(rtMembership);
544     }
545
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);
552             } else {
553                 addRouteTarget(rtc);
554             }
555             rtMembershipsUpdated = true;
556         }
557     }
558
559     @SuppressFBWarnings("UPM_UNCALLED_PRIVATE_METHOD")
560     private static Attributes wrapLongLivedStale(final Attributes attrs) {
561         if (attrs == null) {
562             return STALE_LLGR_ATTRIBUTES;
563         }
564
565         final List<Communities> oldCommunities = attrs.getCommunities();
566         final List<Communities> newCommunities;
567         if (oldCommunities != null) {
568             if (oldCommunities.contains(StaleCommunities.STALE_LLGR)) {
569                 return attrs;
570             }
571             newCommunities = StaleCommunities.create(oldCommunities);
572         } else {
573             newCommunities = STALE_LLGR_COMMUNUTIES;
574         }
575
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();
578     }
579
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) {
584             ret = ret.node(arg);
585         }
586         return ret;
587     }
588
589     private YangInstanceIdentifier effectiveTablePath(final NodeIdentifierWithPredicates tableKey) {
590         return effRibTables.node(TABLES_NID).node(tableKey);
591     }
592
593     private static YangInstanceIdentifier routeMapPath(final RIBSupport<?, ?> ribSupport,
594             final YangInstanceIdentifier tablePath) {
595         return concat(tablePath.node(ROUTES_NID), ribSupport.relativeRoutesPath());
596     }
597
598     private static Optional<NormalizedNode> findRoutesMap(final RIBSupport<?, ?> ribSupport,
599             final Optional<NormalizedNode> optRoutes) {
600         return NormalizedNodes.findNode(optRoutes, ribSupport.relativeRoutesPath());
601     }
602
603     private static ContainerNode extractContainer(final NormalizedNode node) {
604         verify(node instanceof ContainerNode, "Expected ContainerNode, got %s", node);
605         return (ContainerNode) node;
606     }
607
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;
612     }
613
614     private static boolean isLongLivedStale(final ContainerNode attributes) {
615         return NormalizedNodes.findNode(attributes, LLGR_STALE_NID).isPresent();
616     }
617
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()));
621     }
622
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;
630             }
631         }
632         return RIBNormalizedNodes.NOT_UPTODATE_ATTRIBUTES;
633     }
634 }