Cleanup boolean literals
[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_ATTRIBUTES_AID;
14 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ADJRIBIN_NID;
15 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ATTRIBUTES_NID;
16 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.EFFRIBIN_NID;
17 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.LLGR_STALE_NID;
18 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ROUTES_NID;
19 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.TABLES_NID;
20 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.UPTODATE_NID;
21
22 import com.google.common.collect.ImmutableList;
23 import com.google.common.collect.ImmutableMap;
24 import com.google.common.collect.ImmutableSet;
25 import com.google.common.util.concurrent.FluentFuture;
26 import com.google.common.util.concurrent.FutureCallback;
27 import com.google.common.util.concurrent.MoreExecutors;
28 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
29 import java.util.Collection;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Optional;
33 import java.util.Set;
34 import java.util.concurrent.ExecutionException;
35 import java.util.concurrent.atomic.LongAdder;
36 import org.checkerframework.checker.lock.qual.GuardedBy;
37 import org.checkerframework.checker.lock.qual.Holding;
38 import org.opendaylight.mdsal.common.api.CommitInfo;
39 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
40 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
41 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
43 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
44 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
45 import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
46 import org.opendaylight.protocol.bgp.parser.impl.message.update.CommunityUtil;
47 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
48 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
49 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
50 import org.opendaylight.protocol.bgp.rib.impl.spi.RibOutRefresh;
51 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesInstalledCounters;
52 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesReceivedCounters;
53 import org.opendaylight.protocol.bgp.rib.spi.RIBNormalizedNodes;
54 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
55 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRibRoutingPolicy;
56 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryImportParameters;
57 import org.opendaylight.protocol.bgp.route.targetcontrain.spi.ClientRouteTargetContrainCache;
58 import org.opendaylight.protocol.bgp.route.targetcontrain.spi.RouteTargetMembeshipUtil;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.Attributes;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.attributes.Communities;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerRole;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.route.target.constrain.rev180618.RouteTargetConstrainSubsequentAddressFamily;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.route.target.constrain.rev180618.route.target.constrain.routes.route.target.constrain.routes.RouteTargetConstrainRoute;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.Ipv4AddressFamily;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.Ipv6AddressFamily;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.MplsLabeledVpnSubsequentAddressFamily;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.RouteTarget;
69 import org.opendaylight.yangtools.concepts.ListenerRegistration;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
72 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
73 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
76 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
80 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
81 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
82 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
83 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
86
87 /**
88  * Implementation of the BGP import policy. Listens on peer's Adj-RIB-In, inspects all inbound
89  * routes in the context of the advertising peer's role and applies the inbound policy.
90  *
91  * <p>
92  * Inbound policy is applied as follows:
93  *
94  * <p>
95  * 1) if the peer is an eBGP peer, perform attribute replacement and filtering
96  * 2) check if a route is admissible based on attributes attached to it, as well as the
97  * advertising peer's role
98  * 3) output admitting routes with edited attributes into /bgp-rib/rib/peer/effective-rib-in/tables/routes
99  *
100  * <p>
101  * This class is NOT thread-safe.
102  */
103 final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesInstalledCounters,
104         AutoCloseable, ClusteredDOMDataTreeChangeListener {
105
106     private static final Logger LOG = LoggerFactory.getLogger(EffectiveRibInWriter.class);
107     private static final TablesKey IVP4_VPN_TABLE_KEY = new TablesKey(Ipv4AddressFamily.class,
108             MplsLabeledVpnSubsequentAddressFamily.class);
109     private static final TablesKey IVP6_VPN_TABLE_KEY = new TablesKey(Ipv6AddressFamily.class,
110             MplsLabeledVpnSubsequentAddressFamily.class);
111     private static final ImmutableList<Communities> STALE_LLGR_COMMUNUTIES = ImmutableList.of(
112         StaleCommunities.STALE_LLGR);
113     private static final Attributes STALE_LLGR_ATTRIBUTES = new org.opendaylight.yang.gen.v1.urn.opendaylight.params
114             .xml.ns.yang.bgp.message.rev200120.path.attributes.AttributesBuilder()
115             .setCommunities(STALE_LLGR_COMMUNUTIES)
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 DOMDataTreeChangeService service;
123     private final List<RouteTarget> rtMemberships;
124     private final RibOutRefresh vpnTableRefresher;
125     private final ClientRouteTargetContrainCache rtCache;
126     private ListenerRegistration<?> reg;
127     private DOMTransactionChain chain;
128     private final Map<TablesKey, LongAdder> prefixesReceived;
129     private final Map<TablesKey, LongAdder> prefixesInstalled;
130     private final BGPRibRoutingPolicy ribPolicies;
131     private final BGPRouteEntryImportParameters peerImportParameters;
132     private final BGPTableTypeRegistryConsumer tableTypeRegistry;
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         this.registry = requireNonNull(rib.getRibSupportContext());
147         this.chain = requireNonNull(chain);
148         this.peerIId = requireNonNull(peerIId);
149         this.effRibTables = this.peerIId.node(EFFRIBIN_NID);
150         this.prefixesInstalled = buildPrefixesTables(tables);
151         this.prefixesReceived = buildPrefixesTables(tables);
152         this.ribPolicies = requireNonNull(rib.getRibPolicies());
153         this.service = requireNonNull(rib.getService());
154         this.tableTypeRegistry = requireNonNull(tableTypeRegistry);
155         this.peerImportParameters = peer;
156         this.rtMemberships = rtMemberships;
157         this.rtCache = rtCache;
158         this.vpnTableRefresher = rib;
159     }
160
161     public void init() {
162         final DOMDataTreeIdentifier treeId = new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL,
163             this.peerIId.node(ADJRIBIN_NID).node(TABLES_NID));
164         LOG.debug("Registered Effective RIB on {}", this.peerIId);
165         this.reg = requireNonNull(this.service).registerDataTreeChangeListener(treeId, this);
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 onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
176         if (this.chain == null) {
177             LOG.trace("Chain closed. Ignoring Changes : {}", changes);
178             return;
179         }
180
181         LOG.trace("Data changed called to effective RIB. Change : {}", changes);
182         DOMDataTreeWriteTransaction tx = null;
183         for (final DataTreeCandidate tc : changes) {
184             final YangInstanceIdentifier rootPath = tc.getRootPath();
185             final DataTreeCandidateNode root = tc.getRootNode();
186             for (final DataTreeCandidateNode table : root.getChildNodes()) {
187                 if (tx == null) {
188                     tx = this.chain.newWriteOnlyTransaction();
189                 }
190                 changeDataTree(tx, rootPath, root, table);
191             }
192         }
193
194         if (tx != null) {
195             final FluentFuture<? extends CommitInfo> future = tx.commit();
196             this.submitted = future;
197             future.addCallback(new FutureCallback<CommitInfo>() {
198                 @Override
199                 public void onSuccess(final CommitInfo result) {
200                     LOG.trace("Successful commit");
201                 }
202
203                 @Override
204                 public void onFailure(final Throwable trw) {
205                     LOG.error("Failed commit", trw);
206                 }
207             }, MoreExecutors.directExecutor());
208         }
209
210         //Refresh VPN Table if RT Memberships were updated
211         if (this.rtMembershipsUpdated) {
212             this.vpnTableRefresher.refreshTable(IVP4_VPN_TABLE_KEY, this.peerImportParameters.getFromPeerId());
213             this.vpnTableRefresher.refreshTable(IVP6_VPN_TABLE_KEY, this.peerImportParameters.getFromPeerId());
214             this.rtMembershipsUpdated = false;
215         }
216     }
217
218     @Override
219     public synchronized void close() {
220         if (this.reg != null) {
221             this.reg.close();
222             this.reg = null;
223         }
224         if (this.submitted != null) {
225             try {
226                 this.submitted.get();
227             } catch (final InterruptedException | ExecutionException throwable) {
228                 LOG.error("Write routes failed", throwable);
229             }
230         }
231         if (this.chain != null) {
232             this.chain.close();
233             this.chain = null;
234         }
235         this.prefixesReceived.values().forEach(LongAdder::reset);
236         this.prefixesInstalled.values().forEach(LongAdder::reset);
237     }
238
239     @Override
240     public long getPrefixedReceivedCount(final TablesKey tablesKey) {
241         final LongAdder counter = this.prefixesReceived.get(tablesKey);
242         if (counter == null) {
243             return 0;
244         }
245         return counter.longValue();
246     }
247
248     @Override
249     public Set<TablesKey> getTableKeys() {
250         return ImmutableSet.copyOf(this.prefixesReceived.keySet());
251     }
252
253     @Override
254     public boolean isSupported(final TablesKey tablesKey) {
255         return this.prefixesReceived.containsKey(tablesKey);
256     }
257
258     @Override
259     public long getPrefixedInstalledCount(final TablesKey tablesKey) {
260         final LongAdder counter = this.prefixesInstalled.get(tablesKey);
261         if (counter == null) {
262             return 0;
263         }
264         return counter.longValue();
265     }
266
267     @Override
268     public long getTotalPrefixesInstalled() {
269         return this.prefixesInstalled.values().stream().mapToLong(LongAdder::longValue).sum();
270     }
271
272     @Holding("this")
273     private void changeDataTree(final DOMDataTreeWriteTransaction tx, final YangInstanceIdentifier rootPath,
274             final DataTreeCandidateNode root, final DataTreeCandidateNode table) {
275         final PathArgument lastArg = table.getIdentifier();
276         verify(lastArg instanceof NodeIdentifierWithPredicates, "Unexpected type %s in path %s", lastArg.getClass(),
277             rootPath);
278         final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
279         final RIBSupportContext ribContext = this.registry.getRIBSupportContext(tableKey);
280         if (ribContext == null) {
281             LOG.warn("Table {} is not supported, ignoring event", tableKey);
282             return;
283         }
284
285         final YangInstanceIdentifier effectiveTablePath = effectiveTablePath(tableKey);
286         final ModificationType modificationType = root.getModificationType();
287         LOG.debug("Effective table {} modification type {}", effectiveTablePath, modificationType);
288         switch (modificationType) {
289             case DISAPPEARED:
290             case DELETE:
291                 deleteTable(tx, ribContext, effectiveTablePath, table);
292                 break;
293             case APPEARED:
294             case WRITE:
295                 writeTable(tx, ribContext, effectiveTablePath, table);
296                 break;
297             case SUBTREE_MODIFIED:
298                 modifyTable(tx, ribContext, effectiveTablePath, table);
299                 break;
300             case UNMODIFIED:
301                 LOG.info("Ignoring spurious notification on {} data {}", rootPath, table);
302                 break;
303             default:
304                 LOG.warn("Ignoring unhandled root {}", table);
305                 break;
306         }
307     }
308
309     private void deleteTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
310             final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
311         LOG.debug("Delete Effective Table {}", effectiveTablePath);
312         onDeleteTable(ribContext.getRibSupport(), effectiveTablePath, table.getDataBefore());
313         tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath);
314     }
315
316     private void modifyTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
317             final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
318         LOG.debug("Modify Effective Table {}", effectiveTablePath);
319
320         final boolean wasLongLivedStale = isLongLivedStaleTable(table.getDataBefore());
321         final boolean longLivedStale = isLongLivedStaleTable(table.getDataAfter());
322         if (wasLongLivedStale != longLivedStale) {
323             LOG.debug("LLGR_STALE flag flipped {}, overwriting table {}", longLivedStale ? "ON" : "OFF",
324                     effectiveTablePath);
325             writeTable(tx, ribContext, effectiveTablePath, table);
326             return;
327         }
328
329         table.getModifiedChild(ATTRIBUTES_NID).ifPresent(modifiedAttrs -> {
330             final YangInstanceIdentifier effAttrsPath = effectiveTablePath.node(ATTRIBUTES_NID);
331             final Optional<NormalizedNode<?, ?>> optAttrsAfter = modifiedAttrs.getDataAfter();
332             if (optAttrsAfter.isPresent()) {
333                 tx.put(LogicalDatastoreType.OPERATIONAL, effAttrsPath, effectiveAttributes(
334                     NormalizedNodes.findNode(optAttrsAfter.get(), UPTODATE_NID)));
335             } else {
336                 tx.delete(LogicalDatastoreType.OPERATIONAL, effAttrsPath);
337             }
338         });
339
340         table.getModifiedChild(ROUTES_NID).ifPresent(modifiedRoutes -> {
341             final RIBSupport<?, ?, ?, ?> ribSupport = ribContext.getRibSupport();
342             switch (modifiedRoutes.getModificationType()) {
343                 case APPEARED:
344                 case WRITE:
345                     deleteRoutesBefore(tx, ribSupport, effectiveTablePath, modifiedRoutes);
346                     // XXX: YANG Tools seems to have an issue stacking DELETE with child WRITE
347                     tx.put(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ROUTES_NID), EMPTY_ROUTES);
348                     writeRoutesAfter(tx, ribSupport, effectiveTablePath, modifiedRoutes.getDataAfter(), longLivedStale);
349                     break;
350                 case DELETE:
351                 case DISAPPEARED:
352                     deleteRoutesBefore(tx, ribSupport, effectiveTablePath, modifiedRoutes);
353                     tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ROUTES_NID));
354                     break;
355                 case SUBTREE_MODIFIED:
356                     for (DataTreeCandidateNode modifiedRoute : ribSupport.changedRoutes(modifiedRoutes)) {
357                         processRoute(tx, ribSupport, effectiveTablePath, modifiedRoute, longLivedStale);
358                     }
359                     break;
360                 case UNMODIFIED:
361                     // No-op
362                     return;
363                 default:
364                     LOG.warn("Ignoring modified routes {}", modifiedRoutes);
365                     break;
366             }
367         });
368     }
369
370     private void writeTable(final DOMDataTreeWriteTransaction tx, final RIBSupportContext ribContext,
371             final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode table) {
372         LOG.debug("Write Effective Table {}", effectiveTablePath);
373         onDeleteTable(ribContext.getRibSupport(), effectiveTablePath, table.getDataBefore());
374
375         final Optional<NormalizedNode<?, ?>> maybeTableAfter = table.getDataAfter();
376         if (maybeTableAfter.isPresent()) {
377             final MapEntryNode tableAfter = extractMapEntry(maybeTableAfter);
378             ribContext.createEmptyTableStructure(tx, effectiveTablePath);
379
380             final Optional<DataContainerChild<?, ?>> maybeAttrsAfter = tableAfter.getChild(ATTRIBUTES_NID);
381             final boolean longLivedStale;
382             if (maybeAttrsAfter.isPresent()) {
383                 final ContainerNode attrsAfter = extractContainer(maybeAttrsAfter);
384                 longLivedStale = isLongLivedStale(attrsAfter);
385                 tx.put(LogicalDatastoreType.OPERATIONAL, effectiveTablePath.node(ATTRIBUTES_NID),
386                     effectiveAttributes(attrsAfter.getChild(UPTODATE_NID)));
387             } else {
388                 longLivedStale = false;
389             }
390
391             writeRoutesAfter(tx, ribContext.getRibSupport(), effectiveTablePath,
392                 NormalizedNodes.findNode(tableAfter, ROUTES_NID), longLivedStale);
393         }
394     }
395
396     // Performs house-keeping when the contents of a table is deleted
397     private void onDeleteTable(final RIBSupport<?, ?, ?, ?> ribSupport, final YangInstanceIdentifier effectiveTablePath,
398             final Optional<NormalizedNode<?, ?>> tableBefore) {
399         // Routes are special in that we need to process the to keep our counters accurate
400         final Optional<NormalizedNode<?, ?>> maybeRoutesBefore = findRoutesMap(ribSupport,
401                 NormalizedNodes.findNode(tableBefore, ROUTES_NID));
402         if (maybeRoutesBefore.isPresent()) {
403             onRoutesDeleted(ribSupport, effectiveTablePath, extractMap(maybeRoutesBefore).getValue());
404         }
405     }
406
407     private void deleteRoutesBefore(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?, ?, ?> ribSupport,
408             final YangInstanceIdentifier effectiveTablePath, final DataTreeCandidateNode modifiedRoutes) {
409         final Optional<NormalizedNode<?, ?>> maybeRoutesBefore = NormalizedNodes.findNode(
410             modifiedRoutes.getDataBefore(), ribSupport.relativeRoutesPath());
411         if (maybeRoutesBefore.isPresent()) {
412             onRoutesDeleted(ribSupport, effectiveTablePath, extractMap(maybeRoutesBefore).getValue());
413         }
414     }
415
416     private void writeRoutesAfter(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?, ?, ?> ribSupport,
417             final YangInstanceIdentifier effectiveTablePath, final Optional<NormalizedNode<?, ?>> routesAfter,
418             final boolean longLivedStale) {
419         final Optional<NormalizedNode<?, ?>> maybeRoutesAfter = NormalizedNodes.findNode(routesAfter,
420             ribSupport.relativeRoutesPath());
421         if (maybeRoutesAfter.isPresent()) {
422             final YangInstanceIdentifier routesPath = routeMapPath(ribSupport, effectiveTablePath);
423             for (MapEntryNode routeAfter : extractMap(maybeRoutesAfter).getValue()) {
424                 writeRoute(tx, ribSupport, routesPath.node(routeAfter.getIdentifier()), Optional.empty(), routeAfter,
425                     longLivedStale);
426             }
427         }
428     }
429
430     private void onRoutesDeleted(final RIBSupport<?, ?, ?, ?> ribSupport,
431             final YangInstanceIdentifier effectiveTablePath, final Collection<MapEntryNode> deletedRoutes) {
432         if (ribSupport.getSafi() == RouteTargetConstrainSubsequentAddressFamily.class) {
433             final YangInstanceIdentifier routesPath = routeMapPath(ribSupport, effectiveTablePath);
434             for (final MapEntryNode routeBefore : deletedRoutes) {
435                 deleteRouteTarget(ribSupport, routesPath.node(routeBefore.getIdentifier()), routeBefore);
436             }
437             this.rtMembershipsUpdated = true;
438         }
439
440         final TablesKey tablesKey = ribSupport.getTablesKey();
441         CountersUtil.add(prefixesInstalled.get(tablesKey), tablesKey, -deletedRoutes.size());
442     }
443
444     private void processRoute(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?, ?, ?> ribSupport,
445             final YangInstanceIdentifier routesPath, final DataTreeCandidateNode route, final boolean longLivedStale) {
446         LOG.debug("Process route {}", route.getIdentifier());
447         final YangInstanceIdentifier routePath = ribSupport.routePath(routesPath, route.getIdentifier());
448         switch (route.getModificationType()) {
449             case DELETE:
450             case DISAPPEARED:
451                 deleteRoute(tx, ribSupport, routePath, route.getDataBefore().orElse(null));
452                 break;
453             case UNMODIFIED:
454                 // No-op
455                 break;
456             case APPEARED:
457             case SUBTREE_MODIFIED:
458             case WRITE:
459                 writeRoute(tx, ribSupport, routePath, route.getDataBefore(), route.getDataAfter().get(),
460                     longLivedStale);
461                 break;
462             default:
463                 LOG.warn("Ignoring unhandled route {}", route);
464                 break;
465         }
466     }
467
468     private void deleteRoute(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?, ?, ?> ribSupport,
469             final YangInstanceIdentifier routeIdPath, final NormalizedNode<?, ?> route) {
470         handleRouteTarget(ModificationType.DELETE, ribSupport, routeIdPath, route);
471         tx.delete(LogicalDatastoreType.OPERATIONAL, routeIdPath);
472         LOG.debug("Route deleted. routeId={}", routeIdPath);
473         final TablesKey tablesKey = ribSupport.getTablesKey();
474         CountersUtil.decrement(this.prefixesInstalled.get(tablesKey), tablesKey);
475     }
476
477     private void writeRoute(final DOMDataTreeWriteTransaction tx, final RIBSupport<?, ?, ?, ?> ribSupport,
478             final YangInstanceIdentifier routePath, final Optional<NormalizedNode<?, ?>> routeBefore,
479             final NormalizedNode<?, ?> routeAfter, final boolean longLivedStale) {
480         final TablesKey tablesKey = ribSupport.getTablesKey();
481         CountersUtil.increment(this.prefixesReceived.get(tablesKey), tablesKey);
482         // Lookup per-table attributes from RIBSupport
483         final ContainerNode advertisedAttrs = (ContainerNode) NormalizedNodes.findNode(routeAfter,
484             ribSupport.routeAttributesIdentifier()).orElse(null);
485         final Attributes routeAttrs = ribSupport.attributeFromContainerNode(advertisedAttrs);
486         final Optional<Attributes> optEffAtt;
487         // In case we want to add LLGR_STALE we do not process route through policies since it may be
488         // considered as received with LLGR_STALE from peer which is not true.
489         if (longLivedStale) {
490             // LLGR procedures are in effect. If the route is tagged with NO_LLGR, it needs to be removed.
491             final List<Communities> effCommunities = routeAttrs.getCommunities();
492             if (effCommunities != null && effCommunities.contains(CommunityUtil.NO_LLGR)) {
493                 deleteRoute(tx, ribSupport, routePath, routeBefore.orElse(null));
494                 return;
495             }
496             optEffAtt = Optional.of(wrapLongLivedStale(routeAttrs));
497         } else {
498             optEffAtt = ribPolicies.applyImportPolicies(peerImportParameters, routeAttrs,
499                 verifyNotNull(tableTypeRegistry.getAfiSafiType(ribSupport.getTablesKey())));
500         }
501         if (!optEffAtt.isPresent()) {
502             deleteRoute(tx, ribSupport, routePath, routeBefore.orElse(null));
503             return;
504         }
505         handleRouteTarget(ModificationType.WRITE, ribSupport, routePath, routeAfter);
506         tx.put(LogicalDatastoreType.OPERATIONAL, routePath, routeAfter);
507         CountersUtil.increment(this.prefixesInstalled.get(tablesKey), tablesKey);
508
509         final YangInstanceIdentifier attPath = routePath.node(ribSupport.routeAttributesIdentifier());
510         final Attributes attToStore = optEffAtt.get();
511         if (!attToStore.equals(routeAttrs)) {
512             final ContainerNode finalAttribute = ribSupport.attributeToContainerNode(attPath, attToStore);
513             tx.put(LogicalDatastoreType.OPERATIONAL, attPath, finalAttribute);
514         }
515     }
516
517     private void addRouteTarget(final RouteTargetConstrainRoute rtc) {
518         final RouteTarget rtMembership = RouteTargetMembeshipUtil.getRT(rtc);
519         if (PeerRole.Ebgp != this.peerImportParameters.getFromPeerRole()) {
520             this.rtCache.cacheRoute(rtc);
521         }
522         this.rtMemberships.add(rtMembership);
523     }
524
525     private void deleteRouteTarget(final RIBSupport<?, ?, ?, ?> ribSupport, final YangInstanceIdentifier routeIdPath,
526             final NormalizedNode<?, ?> route) {
527         deleteRouteTarget((RouteTargetConstrainRoute) ribSupport.fromNormalizedNode(routeIdPath, route));
528     }
529
530     private void deleteRouteTarget(final RouteTargetConstrainRoute rtc) {
531         final RouteTarget rtMembership = RouteTargetMembeshipUtil.getRT(rtc);
532         if (PeerRole.Ebgp != this.peerImportParameters.getFromPeerRole()) {
533             this.rtCache.uncacheRoute(rtc);
534         }
535         this.rtMemberships.remove(rtMembership);
536     }
537
538     private void handleRouteTarget(final ModificationType modificationType, final RIBSupport<?, ?, ?, ?> ribSupport,
539             final YangInstanceIdentifier routeIdPath, final NormalizedNode<?, ?> route) {
540         if (ribSupport.getSafi() == RouteTargetConstrainSubsequentAddressFamily.class) {
541             final RouteTargetConstrainRoute rtc =
542                 (RouteTargetConstrainRoute) ribSupport.fromNormalizedNode(routeIdPath, route);
543             if (ModificationType.DELETE == modificationType) {
544                 deleteRouteTarget(rtc);
545             } else {
546                 addRouteTarget(rtc);
547             }
548             this.rtMembershipsUpdated = true;
549         }
550     }
551
552     @SuppressFBWarnings("UPM_UNCALLED_PRIVATE_METHOD")
553     private static Attributes wrapLongLivedStale(final Attributes attrs) {
554         if (attrs == null) {
555             return STALE_LLGR_ATTRIBUTES;
556         }
557
558         final List<Communities> oldCommunities = attrs.getCommunities();
559         final List<Communities> newCommunities;
560         if (oldCommunities != null) {
561             if (oldCommunities.contains(StaleCommunities.STALE_LLGR)) {
562                 return attrs;
563             }
564             newCommunities = StaleCommunities.create(oldCommunities);
565         } else {
566             newCommunities = STALE_LLGR_COMMUNUTIES;
567         }
568
569         return new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120
570                 .path.attributes.AttributesBuilder(attrs).setCommunities(newCommunities).build();
571     }
572
573     // XXX: this should be moved to YangInstanceIdentifier at some point
574     private static YangInstanceIdentifier concat(final YangInstanceIdentifier parent, final List<PathArgument> args) {
575         YangInstanceIdentifier ret = parent;
576         for (PathArgument arg : args) {
577             ret = ret.node(arg);
578         }
579         return ret;
580     }
581
582     private YangInstanceIdentifier effectiveTablePath(final NodeIdentifierWithPredicates tableKey) {
583         return this.effRibTables.node(TABLES_NID).node(tableKey);
584     }
585
586     private static YangInstanceIdentifier routeMapPath(final RIBSupport<?, ?, ?, ?> ribSupport,
587             final YangInstanceIdentifier tablePath) {
588         return concat(tablePath.node(ROUTES_NID), ribSupport.relativeRoutesPath());
589     }
590
591     private static Optional<NormalizedNode<?, ?>> findRoutesMap(final RIBSupport<?, ?, ?, ?> ribSupport,
592             final Optional<NormalizedNode<?, ?>> optRoutes) {
593         return NormalizedNodes.findNode(optRoutes, ribSupport.relativeRoutesPath());
594     }
595
596     private static ContainerNode extractContainer(final Optional<? extends NormalizedNode<?, ?>> optNode) {
597         final NormalizedNode<?, ?> node = optNode.get();
598         verify(node instanceof ContainerNode, "Expected ContainerNode, got %s", node);
599         return (ContainerNode) node;
600     }
601
602     private static MapNode extractMap(final Optional<? extends NormalizedNode<?, ?>> optNode) {
603         final NormalizedNode<?, ?> node = optNode.get();
604         verify(node instanceof MapNode, "Expected MapNode, got %s", node);
605         return (MapNode) node;
606     }
607
608     private static MapEntryNode extractMapEntry(final Optional<? extends NormalizedNode<?, ?>> optNode) {
609         final NormalizedNode<?, ?> node = optNode.get();
610         verify(node instanceof MapEntryNode, "Expected MapEntryNode, got %s", node);
611         return (MapEntryNode) node;
612     }
613
614     private static boolean isLongLivedStale(final ContainerNode attributes) {
615         return NormalizedNodes.findNode(attributes, ADJRIBIN_ATTRIBUTES_AID, 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));
621     }
622
623     private static ContainerNode effectiveAttributes(final Optional<? extends NormalizedNode<?, ?>> optUptodate) {
624         return optUptodate.map(leaf -> {
625             final Object value = leaf.getValue();
626             verify(value instanceof Boolean, "Expected boolean uptodate, got %s", value);
627             return ((Boolean) value).booleanValue() ? RIBNormalizedNodes.UPTODATE_ATTRIBUTES
628                     : RIBNormalizedNodes.NOT_UPTODATE_ATTRIBUTES;
629         }).orElse(RIBNormalizedNodes.NOT_UPTODATE_ATTRIBUTES);
630     }
631 }