2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.protocol.bgp.rib.impl;
10 import static com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.util.concurrent.FluentFuture;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import java.util.Collection;
20 import java.util.List;
22 import java.util.Optional;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.atomic.LongAdder;
26 import javax.annotation.Nonnull;
27 import javax.annotation.concurrent.GuardedBy;
28 import javax.annotation.concurrent.NotThreadSafe;
29 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
30 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
31 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
32 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
33 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
34 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
35 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
36 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
37 import org.opendaylight.mdsal.common.api.CommitInfo;
38 import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
39 import org.opendaylight.protocol.bgp.parser.impl.message.update.CommunityUtil;
40 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
41 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
42 import org.opendaylight.protocol.bgp.rib.impl.spi.RibOutRefresh;
43 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesInstalledCounters;
44 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesReceivedCounters;
45 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
46 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRibRoutingPolicy;
47 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryImportParameters;
48 import org.opendaylight.protocol.bgp.route.targetcontrain.spi.ClientRouteTargetContrainCache;
49 import org.opendaylight.protocol.bgp.route.targetcontrain.spi.RouteTargetMembeshipUtil;
50 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.AfiSafiType;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.Attributes;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.attributes.Communities;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerRole;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.Route;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.Peer;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.PeerKey;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.AdjRibIn;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.EffectiveRibIn;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.Routes;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.Ipv4AddressFamily;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.Ipv6AddressFamily;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.MplsLabeledVpnSubsequentAddressFamily;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.RouteTarget;
67 import org.opendaylight.yangtools.concepts.ListenerRegistration;
68 import org.opendaylight.yangtools.yang.binding.ChildOf;
69 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
70 import org.opendaylight.yangtools.yang.binding.DataObject;
71 import org.opendaylight.yangtools.yang.binding.Identifiable;
72 import org.opendaylight.yangtools.yang.binding.Identifier;
73 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
74 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
75 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
76 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
77 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
82 * Implementation of the BGP import policy. Listens on peer's Adj-RIB-In, inspects all inbound
83 * routes in the context of the advertising peer's role and applies the inbound policy.
85 * Inbound policy is applied as follows:
87 * 1) if the peer is an eBGP peer, perform attribute replacement and filtering
88 * 2) check if a route is admissible based on attributes attached to it, as well as the
89 * advertising peer's role
90 * 3) output admitting routes with edited attributes into /bgp-rib/rib/peer/effective-rib-in/tables/routes
93 final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesInstalledCounters,
94 AutoCloseable, ClusteredDataTreeChangeListener<Tables> {
96 private static final Logger LOG = LoggerFactory.getLogger(EffectiveRibInWriter.class);
97 static final NodeIdentifier TABLE_ROUTES = new NodeIdentifier(Routes.QNAME);
98 private static final TablesKey IVP4_VPN_TABLE_KEY = new TablesKey(Ipv4AddressFamily.class,
99 MplsLabeledVpnSubsequentAddressFamily.class);
100 private static final TablesKey IVP6_VPN_TABLE_KEY = new TablesKey(Ipv6AddressFamily.class,
101 MplsLabeledVpnSubsequentAddressFamily.class);
102 private static final ImmutableList<Communities> STALE_LLGR_COMMUNUTIES = ImmutableList.of(
103 StaleCommunities.STALE_LLGR);
104 private static final Attributes STALE_LLGR_ATTRIBUTES = new org.opendaylight.yang.gen.v1.urn.opendaylight.params
105 .xml.ns.yang.bgp.message.rev180329.path.attributes.AttributesBuilder()
106 .setCommunities(STALE_LLGR_COMMUNUTIES)
109 private final RIBSupportContextRegistry registry;
110 private final KeyedInstanceIdentifier<Peer, PeerKey> peerIId;
111 private final InstanceIdentifier<EffectiveRibIn> effRibTables;
112 private final DataBroker databroker;
113 private final List<RouteTarget> rtMemberships;
114 private final RibOutRefresh vpnTableRefresher;
115 private final ClientRouteTargetContrainCache rtCache;
116 private ListenerRegistration<?> reg;
117 private BindingTransactionChain chain;
118 private final Map<TablesKey, LongAdder> prefixesReceived;
119 private final Map<TablesKey, LongAdder> prefixesInstalled;
120 private final BGPRibRoutingPolicy ribPolicies;
121 private final BGPRouteEntryImportParameters peerImportParameters;
122 private final BGPTableTypeRegistryConsumer tableTypeRegistry;
124 private FluentFuture<? extends CommitInfo> submitted;
125 private boolean rtMembershipsUpdated;
127 EffectiveRibInWriter(
128 final BGPRouteEntryImportParameters peer,
130 final BindingTransactionChain chain,
131 final KeyedInstanceIdentifier<Peer, PeerKey> peerIId,
132 final Set<TablesKey> tables,
133 final BGPTableTypeRegistryConsumer tableTypeRegistry,
134 final List<RouteTarget> rtMemberships,
135 final ClientRouteTargetContrainCache rtCache) {
136 this.registry = requireNonNull(rib.getRibSupportContext());
137 this.chain = requireNonNull(chain);
138 this.peerIId = requireNonNull(peerIId);
139 this.effRibTables = this.peerIId.child(EffectiveRibIn.class);
140 this.prefixesInstalled = buildPrefixesTables(tables);
141 this.prefixesReceived = buildPrefixesTables(tables);
142 this.ribPolicies = requireNonNull(rib.getRibPolicies());
143 this.databroker = requireNonNull(rib.getDataBroker());
144 this.tableTypeRegistry = requireNonNull(tableTypeRegistry);
145 this.peerImportParameters = peer;
146 this.rtMemberships = rtMemberships;
147 this.rtCache = rtCache;
148 this.vpnTableRefresher = rib;
152 final DataTreeIdentifier<Tables> treeId = new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL,
153 this.peerIId.child(AdjRibIn.class).child(Tables.class));
154 LOG.debug("Registered Effective RIB on {}", this.peerIId);
155 this.reg = requireNonNull(this.databroker).registerDataTreeChangeListener(treeId, this);
158 private static Map<TablesKey, LongAdder> buildPrefixesTables(final Set<TablesKey> tables) {
159 final ImmutableMap.Builder<TablesKey, LongAdder> b = ImmutableMap.builder();
160 tables.forEach(table -> b.put(table, new LongAdder()));
165 public synchronized void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<Tables>> changes) {
166 if (this.chain == null) {
167 LOG.trace("Chain closed. Ignoring Changes : {}", changes);
171 LOG.trace("Data changed called to effective RIB. Change : {}", changes);
172 if (!changes.isEmpty()) {
173 processModifications(changes);
176 //Refresh VPN Table if RT Memberships were updated
177 if (this.rtMembershipsUpdated) {
178 this.vpnTableRefresher.refreshTable(IVP4_VPN_TABLE_KEY, this.peerImportParameters.getFromPeerId());
179 this.vpnTableRefresher.refreshTable(IVP6_VPN_TABLE_KEY, this.peerImportParameters.getFromPeerId());
180 this.rtMembershipsUpdated = false;
185 @SuppressWarnings("unchecked")
186 private void processModifications(final Collection<DataTreeModification<Tables>> changes) {
187 final WriteTransaction tx = this.chain.newWriteOnlyTransaction();
188 for (final DataTreeModification<Tables> tc : changes) {
189 final DataObjectModification<Tables> table = tc.getRootNode();
190 final DataObjectModification.ModificationType modificationType = table.getModificationType();
191 switch (modificationType) {
193 final Tables removeTable = table.getDataBefore();
194 final TablesKey tableKey = removeTable.key();
195 final KeyedInstanceIdentifier<Tables, TablesKey> effectiveTablePath
196 = this.effRibTables.child(Tables.class, tableKey);
197 LOG.debug("Delete Effective Table {} modification type {}, "
198 , effectiveTablePath, modificationType);
199 tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath);
200 CountersUtil.decrement(this.prefixesInstalled.get(tableKey), tableKey);
202 case SUBTREE_MODIFIED:
203 final Tables before = table.getDataBefore();
204 final Tables after = table.getDataAfter();
205 final TablesKey tk = after.key();
206 LOG.debug("Process table {} type {}, dataAfter {}, dataBefore {}",
207 tk, modificationType, after, before);
209 final KeyedInstanceIdentifier<Tables, TablesKey> tablePath
210 = this.effRibTables.child(Tables.class, tk);
211 final RIBSupport ribSupport = this.registry.getRIBSupport(tk);
212 if (ribSupport == null) {
216 final DataObjectModification<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp
217 .rib.rev180329.rib.tables.Attributes> adjRibAttrsChanged = table.getModifiedChildContainer(
218 org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329
219 .rib.tables.Attributes.class);
220 if (adjRibAttrsChanged != null) {
221 tx.put(LogicalDatastoreType.OPERATIONAL,
222 tablePath.child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp
223 .rib.rev180329.rib.tables.Attributes.class), adjRibAttrsChanged.getDataAfter());
226 final DataObjectModification routesChangesContainer = table.getModifiedChildContainer(
227 ribSupport.routesCaseClass(), ribSupport.routesContainerClass());
229 if (routesChangesContainer == null) {
232 updateRoutes(tx, tk, ribSupport, tablePath, routesChangesContainer.getModifiedChildren());
235 writeTable(tx, table);
238 LOG.warn("Ignoring unhandled root {}", table);
243 final FluentFuture<? extends CommitInfo> future = tx.commit();
244 this.submitted = future;
245 future.addCallback(new FutureCallback<CommitInfo>() {
247 public void onSuccess(final CommitInfo result) {
248 LOG.trace("Successful commit");
252 public void onFailure(final Throwable trw) {
253 LOG.error("Failed commit", trw);
255 }, MoreExecutors.directExecutor());
258 @SuppressWarnings("unchecked")
259 private <C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
260 R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>> void updateRoutes(
261 final WriteTransaction tx,
262 final TablesKey tableKey, final RIBSupport<C, S, R, I> ribSupport,
263 final KeyedInstanceIdentifier<Tables, TablesKey> tablePath,
264 final Collection<DataObjectModification<R>> routeChanges) {
266 Class<? extends AfiSafiType> afiSafiType = null;
267 for (final DataObjectModification<R> routeChanged : routeChanges) {
268 final PathArgument routeChangeId = routeChanged.getIdentifier();
269 verify(routeChangeId instanceof IdentifiableItem, "Route change %s has invalid identifier %s",
270 routeChanged, routeChangeId);
271 final I routeKey = ((IdentifiableItem<R, I>) routeChangeId).getKey();
273 switch (routeChanged.getModificationType()) {
274 case SUBTREE_MODIFIED:
276 if (afiSafiType == null) {
277 afiSafiType = tableTypeRegistry.getAfiSafiType(ribSupport.getTablesKey()).get();
280 writeRoutes(tx, tableKey, afiSafiType, ribSupport, tablePath, routeKey,
281 routeChanged.getDataAfter(), false);
284 final InstanceIdentifier<R> routeIID = ribSupport.createRouteIdentifier(tablePath, routeKey);
285 deleteRoutes(routeIID, routeChanged.getDataBefore(), tx);
291 private <C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
292 R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>> void writeRoutes(
293 final WriteTransaction tx, final TablesKey tk, final Class<? extends AfiSafiType> afiSafiType,
294 final RIBSupport<C, S, R, I> ribSupport, final KeyedInstanceIdentifier<Tables, TablesKey> tablePath,
295 final I routeKey, final R route, final boolean longLivedStale) {
296 final InstanceIdentifier<R> routeIID = ribSupport.createRouteIdentifier(tablePath, routeKey);
297 CountersUtil.increment(this.prefixesReceived.get(tk), tk);
299 final Attributes routeAttrs = route.getAttributes();
300 final Optional<Attributes> optEffAtt;
301 // In case we want to add LLGR_STALE we do not process route through policies since it may be
302 // considered as received with LLGR_STALE from peer which is not true.
303 if (longLivedStale) {
304 // LLGR procedures are in effect. If the route is tagged with NO_LLGR, it needs to be removed.
305 final List<Communities> effCommunities = routeAttrs.getCommunities();
306 if (effCommunities != null && effCommunities.contains(CommunityUtil.NO_LLGR)) {
307 deleteRoutes(routeIID, route, tx);
310 optEffAtt = Optional.of(wrapLongLivedStale(routeAttrs));
312 optEffAtt = this.ribPolicies.applyImportPolicies(this.peerImportParameters, routeAttrs, afiSafiType);
314 if (!optEffAtt.isPresent()) {
315 deleteRoutes(routeIID, route, tx);
319 final Optional<RouteTarget> rtMembership = RouteTargetMembeshipUtil.getRT(route);
320 if (rtMembership.isPresent()) {
321 final RouteTarget rt = rtMembership.get();
322 if (PeerRole.Ebgp != this.peerImportParameters.getFromPeerRole()) {
323 this.rtCache.cacheRoute(route);
325 this.rtMemberships.add(rt);
326 this.rtMembershipsUpdated = true;
328 CountersUtil.increment(this.prefixesInstalled.get(tk), tk);
329 tx.put(LogicalDatastoreType.OPERATIONAL, routeIID, route);
330 tx.put(LogicalDatastoreType.OPERATIONAL, routeIID.child(Attributes.class), optEffAtt.get());
333 private static Attributes wrapLongLivedStale(final Attributes attrs) {
335 return STALE_LLGR_ATTRIBUTES;
338 final List<Communities> oldCommunities = attrs.getCommunities();
339 final List<Communities> newCommunities;
340 if (oldCommunities != null) {
341 if (oldCommunities.contains(StaleCommunities.STALE_LLGR)) {
344 newCommunities = StaleCommunities.create(oldCommunities);
346 newCommunities = STALE_LLGR_COMMUNUTIES;
349 return new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329
350 .path.attributes.AttributesBuilder(attrs).setCommunities(newCommunities).build();
353 private <R extends Route> void deleteRoutes(final InstanceIdentifier<R> routeIID,
354 final R route, final WriteTransaction tx) {
355 final Optional<RouteTarget> rtMembership = RouteTargetMembeshipUtil.getRT(route);
356 if (rtMembership.isPresent()) {
357 if(PeerRole.Ebgp != this.peerImportParameters.getFromPeerRole()) {
358 this.rtCache.uncacheRoute(route);
360 this.rtMemberships.remove(rtMembership.get());
361 this.rtMembershipsUpdated = true;
363 tx.delete(LogicalDatastoreType.OPERATIONAL, routeIID);
366 @SuppressWarnings("unchecked")
367 private void writeTable(final WriteTransaction tx, final DataObjectModification<Tables> table) {
368 final Tables newTable = table.getDataAfter();
369 if (newTable == null) {
372 final TablesKey tableKey = newTable.key();
373 final KeyedInstanceIdentifier<Tables, TablesKey> tablePath
374 = this.effRibTables.child(Tables.class, tableKey);
376 // Create an empty table
377 LOG.trace("Create Empty table at {}", tablePath);
378 if (table.getDataBefore() == null) {
379 tx.put(LogicalDatastoreType.OPERATIONAL, tablePath, new TablesBuilder()
380 .withKey(tableKey).setAfi(tableKey.getAfi()).setSafi(tableKey.getSafi())
381 .setAttributes(newTable.getAttributes()).build());
384 final RIBSupport ribSupport = this.registry.getRIBSupport(tableKey);
385 final Routes routes = newTable.getRoutes();
386 if (ribSupport == null || routes == null) {
390 final DataObjectModification routesChangesContainer =
391 table.getModifiedChildContainer(ribSupport.routesCaseClass(), ribSupport.routesContainerClass());
393 if (routesChangesContainer == null) {
396 updateRoutes(tx, tableKey, ribSupport, tablePath, routesChangesContainer.getModifiedChildren());
400 public synchronized void close() {
401 if (this.reg != null) {
405 if (this.submitted != null) {
407 this.submitted.get();
408 } catch (final InterruptedException | ExecutionException throwable) {
409 LOG.error("Write routes failed", throwable);
412 if (this.chain != null) {
416 this.prefixesReceived.values().forEach(LongAdder::reset);
417 this.prefixesInstalled.values().forEach(LongAdder::reset);
421 public long getPrefixedReceivedCount(final TablesKey tablesKey) {
422 final LongAdder counter = this.prefixesReceived.get(tablesKey);
423 if (counter == null) {
426 return counter.longValue();
430 public Set<TablesKey> getTableKeys() {
431 return ImmutableSet.copyOf(this.prefixesReceived.keySet());
435 public boolean isSupported(final TablesKey tablesKey) {
436 return this.prefixesReceived.containsKey(tablesKey);
440 public long getPrefixedInstalledCount(final TablesKey tablesKey) {
441 final LongAdder counter = this.prefixesInstalled.get(tablesKey);
442 if (counter == null) {
445 return counter.longValue();
449 public long getTotalPrefixesInstalled() {
450 return this.prefixesInstalled.values().stream().mapToLong(LongAdder::longValue).sum();