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.ImmutableMap;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.util.concurrent.FluentFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.util.Collection;
19 import java.util.List;
21 import java.util.Optional;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.atomic.LongAdder;
25 import javax.annotation.Nonnull;
26 import javax.annotation.concurrent.GuardedBy;
27 import javax.annotation.concurrent.NotThreadSafe;
28 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
29 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
30 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
31 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
32 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
33 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
34 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
35 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
36 import org.opendaylight.mdsal.common.api.CommitInfo;
37 import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
38 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
39 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
40 import org.opendaylight.protocol.bgp.rib.impl.spi.RibOutRefresh;
41 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesInstalledCounters;
42 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesReceivedCounters;
43 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
44 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRibRoutingPolicy;
45 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryImportParameters;
46 import org.opendaylight.protocol.bgp.route.targetcontrain.spi.ClientRouteTargetContrainCache;
47 import org.opendaylight.protocol.bgp.route.targetcontrain.spi.RouteTargetMembeshipUtil;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.Attributes;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerRole;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.Route;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.Peer;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.PeerKey;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.AdjRibIn;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.EffectiveRibIn;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.Routes;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.Ipv4AddressFamily;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.Ipv6AddressFamily;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.MplsLabeledVpnSubsequentAddressFamily;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.RouteTarget;
63 import org.opendaylight.yangtools.concepts.ListenerRegistration;
64 import org.opendaylight.yangtools.yang.binding.ChildOf;
65 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
66 import org.opendaylight.yangtools.yang.binding.DataObject;
67 import org.opendaylight.yangtools.yang.binding.Identifiable;
68 import org.opendaylight.yangtools.yang.binding.Identifier;
69 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
70 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
71 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
72 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
73 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
78 * Implementation of the BGP import policy. Listens on peer's Adj-RIB-In, inspects all inbound
79 * routes in the context of the advertising peer's role and applies the inbound policy.
81 * Inbound policy is applied as follows:
83 * 1) if the peer is an eBGP peer, perform attribute replacement and filtering
84 * 2) check if a route is admissible based on attributes attached to it, as well as the
85 * advertising peer's role
86 * 3) output admitting routes with edited attributes into /bgp-rib/rib/peer/effective-rib-in/tables/routes
89 final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesInstalledCounters,
90 AutoCloseable, ClusteredDataTreeChangeListener<Tables> {
92 private static final Logger LOG = LoggerFactory.getLogger(EffectiveRibInWriter.class);
93 static final NodeIdentifier TABLE_ROUTES = new NodeIdentifier(Routes.QNAME);
94 private static final TablesKey IVP4_VPN_TABLE_KEY = new TablesKey(Ipv4AddressFamily.class,
95 MplsLabeledVpnSubsequentAddressFamily.class);
96 private static final TablesKey IVP6_VPN_TABLE_KEY = new TablesKey(Ipv6AddressFamily.class,
97 MplsLabeledVpnSubsequentAddressFamily.class);
98 private final RIBSupportContextRegistry registry;
99 private final KeyedInstanceIdentifier<Peer, PeerKey> peerIId;
100 private final InstanceIdentifier<EffectiveRibIn> effRibTables;
101 private final DataBroker databroker;
102 private final List<RouteTarget> rtMemberships;
103 private final RibOutRefresh vpnTableRefresher;
104 private final ClientRouteTargetContrainCache rtCache;
105 private ListenerRegistration<?> reg;
106 private BindingTransactionChain chain;
107 private final Map<TablesKey, LongAdder> prefixesReceived;
108 private final Map<TablesKey, LongAdder> prefixesInstalled;
109 private final BGPRibRoutingPolicy ribPolicies;
110 private final BGPRouteEntryImportParameters peerImportParameters;
111 private final BGPTableTypeRegistryConsumer tableTypeRegistry;
113 private FluentFuture<? extends CommitInfo> submitted;
114 private boolean rtMembershipsUpdated;
116 EffectiveRibInWriter(
117 final BGPRouteEntryImportParameters peer,
119 final BindingTransactionChain chain,
120 final KeyedInstanceIdentifier<Peer, PeerKey> peerIId,
121 final Set<TablesKey> tables,
122 final BGPTableTypeRegistryConsumer tableTypeRegistry,
123 final List<RouteTarget> rtMemberships,
124 final ClientRouteTargetContrainCache rtCache) {
125 this.registry = requireNonNull(rib.getRibSupportContext());
126 this.chain = requireNonNull(chain);
127 this.peerIId = requireNonNull(peerIId);
128 this.effRibTables = this.peerIId.child(EffectiveRibIn.class);
129 this.prefixesInstalled = buildPrefixesTables(tables);
130 this.prefixesReceived = buildPrefixesTables(tables);
131 this.ribPolicies = requireNonNull(rib.getRibPolicies());
132 this.databroker = requireNonNull(rib.getDataBroker());
133 this.tableTypeRegistry = requireNonNull(tableTypeRegistry);
134 this.peerImportParameters = peer;
135 this.rtMemberships = rtMemberships;
136 this.rtCache = rtCache;
137 this.vpnTableRefresher = rib;
141 final DataTreeIdentifier<Tables> treeId = new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL,
142 this.peerIId.child(AdjRibIn.class).child(Tables.class));
143 LOG.debug("Registered Effective RIB on {}", this.peerIId);
144 this.reg = requireNonNull(this.databroker).registerDataTreeChangeListener(treeId, this);
147 private static Map<TablesKey, LongAdder> buildPrefixesTables(final Set<TablesKey> tables) {
148 final ImmutableMap.Builder<TablesKey, LongAdder> b = ImmutableMap.builder();
149 tables.forEach(table -> b.put(table, new LongAdder()));
154 @SuppressWarnings("unchecked")
155 public synchronized void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<Tables>> changes) {
156 if (this.chain == null) {
157 LOG.trace("Chain closed. Ignoring Changes : {}", changes);
160 LOG.trace("Data changed called to effective RIB. Change : {}", changes);
161 WriteTransaction tx = null;
162 for (final DataTreeModification<Tables> tc : changes) {
163 final DataObjectModification<Tables> table = tc.getRootNode();
165 tx = this.chain.newWriteOnlyTransaction();
167 final DataObjectModification.ModificationType modificationType = table.getModificationType();
168 switch (modificationType) {
170 final Tables removeTable = table.getDataBefore();
171 final TablesKey tableKey = removeTable.key();
172 final KeyedInstanceIdentifier<Tables, TablesKey> effectiveTablePath
173 = this.effRibTables.child(Tables.class, tableKey);
174 LOG.debug("Delete Effective Table {} modification type {}, "
175 , effectiveTablePath, modificationType);
176 tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath);
177 CountersUtil.decrement(this.prefixesInstalled.get(tableKey), tableKey);
179 case SUBTREE_MODIFIED:
180 final Tables before = table.getDataBefore();
181 final Tables after = table.getDataAfter();
182 final TablesKey tk = after.key();
183 LOG.debug("Process table {} type {}, dataAfter {}, dataBefore {}",
184 tk, modificationType, after, before);
186 final KeyedInstanceIdentifier<Tables, TablesKey> tablePath
187 = this.effRibTables.child(Tables.class, tk);
188 final RIBSupport ribSupport = this.registry.getRIBSupport(tk);
189 if (ribSupport == null) {
193 final DataObjectModification<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp
194 .rib.rev180329.rib.tables.Attributes> adjRibAttrsChanged = table.getModifiedChildContainer(
195 org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329
196 .rib.tables.Attributes.class);
197 if (adjRibAttrsChanged != null) {
198 tx.put(LogicalDatastoreType.OPERATIONAL,
199 tablePath.child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp
200 .rib.rev180329.rib.tables.Attributes.class), adjRibAttrsChanged.getDataAfter());
203 final DataObjectModification routesChangesContainer = table.getModifiedChildContainer(
204 ribSupport.routesCaseClass(), ribSupport.routesContainerClass());
206 if (routesChangesContainer == null) {
209 updateRoutes(tx, tk, ribSupport, tablePath, routesChangesContainer.getModifiedChildren());
212 writeTable(tx, table);
215 LOG.warn("Ignoring unhandled root {}", table);
220 final FluentFuture<? extends CommitInfo> future = tx.commit();
221 this.submitted = future;
222 future.addCallback(new FutureCallback<CommitInfo>() {
224 public void onSuccess(final CommitInfo result) {
225 LOG.trace("Successful commit");
229 public void onFailure(final Throwable trw) {
230 LOG.error("Failed commit", trw);
232 }, MoreExecutors.directExecutor());
235 //Refresh VPN Table if RT Memberships were updated
236 if (this.rtMembershipsUpdated) {
237 this.vpnTableRefresher.refreshTable(IVP4_VPN_TABLE_KEY, this.peerImportParameters.getFromPeerId());
238 this.vpnTableRefresher.refreshTable(IVP6_VPN_TABLE_KEY, this.peerImportParameters.getFromPeerId());
239 this.rtMembershipsUpdated = false;
243 @SuppressWarnings("unchecked")
244 private <C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
245 R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>> void updateRoutes(
246 final WriteTransaction tx,
247 final TablesKey tableKey, final RIBSupport<C, S, R, I> ribSupport,
248 final KeyedInstanceIdentifier<Tables, TablesKey> tablePath,
249 final Collection<DataObjectModification<R>> routeChanges) {
250 for (final DataObjectModification<R> routeChanged : routeChanges) {
251 final PathArgument routeChangeId = routeChanged.getIdentifier();
252 verify(routeChangeId instanceof IdentifiableItem, "Route change %s has invalid identifier %s",
253 routeChanged, routeChangeId);
254 final I routeKey = ((IdentifiableItem<R, I>) routeChangeId).getKey();
256 switch (routeChanged.getModificationType()) {
257 case SUBTREE_MODIFIED:
259 writeRoutes(tx, tableKey, ribSupport, tablePath, routeKey, routeChanged.getDataAfter());
262 final InstanceIdentifier<R> routeIID = ribSupport.createRouteIdentifier(tablePath, routeKey);
263 deleteRoutes(routeIID, routeChanged.getDataBefore(), tx);
269 private <C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
270 R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>> void writeRoutes(
271 final WriteTransaction tx, final TablesKey tk, final RIBSupport<C, S, R, I> ribSupport,
272 final KeyedInstanceIdentifier<Tables, TablesKey> tablePath, final I routeKey,
274 final InstanceIdentifier<R> routeIID = ribSupport.createRouteIdentifier(tablePath, routeKey);
275 CountersUtil.increment(this.prefixesReceived.get(tk), tk);
276 final Optional<Attributes> effAtt = this.ribPolicies
277 .applyImportPolicies(this.peerImportParameters, route.getAttributes(),
278 tableTypeRegistry.getAfiSafiType(ribSupport.getTablesKey()).get());
279 if (effAtt.isPresent()) {
280 final Optional<RouteTarget> rtMembership = RouteTargetMembeshipUtil.getRT(route);
281 if (rtMembership.isPresent()) {
282 final RouteTarget rt = rtMembership.get();
283 if(PeerRole.Ebgp != this.peerImportParameters.getFromPeerRole()) {
284 this.rtCache.cacheRoute(route);
286 this.rtMemberships.add(rt);
287 this.rtMembershipsUpdated = true;
289 CountersUtil.increment(this.prefixesInstalled.get(tk), tk);
290 tx.put(LogicalDatastoreType.OPERATIONAL, routeIID, route);
291 tx.put(LogicalDatastoreType.OPERATIONAL, routeIID.child(Attributes.class), effAtt.get());
293 deleteRoutes(routeIID, route, tx);
298 private <R extends Route> void deleteRoutes(final InstanceIdentifier<R> routeIID,
299 final R route, final WriteTransaction tx) {
300 final Optional<RouteTarget> rtMembership = RouteTargetMembeshipUtil.getRT(route);
301 if (rtMembership.isPresent()) {
302 if(PeerRole.Ebgp != this.peerImportParameters.getFromPeerRole()) {
303 this.rtCache.uncacheRoute(route);
305 this.rtMemberships.remove(rtMembership.get());
306 this.rtMembershipsUpdated = true;
308 tx.delete(LogicalDatastoreType.OPERATIONAL, routeIID);
311 @SuppressWarnings("unchecked")
312 private void writeTable(final WriteTransaction tx, final DataObjectModification<Tables> table) {
313 final Tables newTable = table.getDataAfter();
314 if (newTable == null) {
317 final TablesKey tableKey = newTable.key();
318 final KeyedInstanceIdentifier<Tables, TablesKey> tablePath
319 = this.effRibTables.child(Tables.class, tableKey);
321 // Create an empty table
322 LOG.trace("Create Empty table at {}", tablePath);
323 if (table.getDataBefore() == null) {
324 tx.put(LogicalDatastoreType.OPERATIONAL, tablePath, new TablesBuilder()
325 .setAfi(tableKey.getAfi()).setSafi(tableKey.getSafi())
326 .setAttributes(newTable.getAttributes()).build());
329 final RIBSupport ribSupport = this.registry.getRIBSupport(tableKey);
330 final Routes routes = newTable.getRoutes();
331 if (ribSupport == null || routes == null) {
335 final DataObjectModification routesChangesContainer =
336 table.getModifiedChildContainer(ribSupport.routesCaseClass(), ribSupport.routesContainerClass());
338 if (routesChangesContainer == null) {
341 updateRoutes(tx, tableKey, ribSupport, tablePath, routesChangesContainer.getModifiedChildren());
345 public synchronized void close() {
346 if (this.reg != null) {
350 if (this.submitted != null) {
352 this.submitted.get();
353 } catch (final InterruptedException | ExecutionException throwable) {
354 LOG.error("Write routes failed", throwable);
357 if (this.chain != null) {
361 this.prefixesReceived.values().forEach(LongAdder::reset);
362 this.prefixesInstalled.values().forEach(LongAdder::reset);
366 public long getPrefixedReceivedCount(final TablesKey tablesKey) {
367 final LongAdder counter = this.prefixesReceived.get(tablesKey);
368 if (counter == null) {
371 return counter.longValue();
375 public Set<TablesKey> getTableKeys() {
376 return ImmutableSet.copyOf(this.prefixesReceived.keySet());
380 public boolean isSupported(final TablesKey tablesKey) {
381 return this.prefixesReceived.containsKey(tablesKey);
385 public long getPrefixedInstalledCount(final TablesKey tablesKey) {
386 final LongAdder counter = this.prefixesInstalled.get(tablesKey);
387 if (counter == null) {
390 return counter.longValue();
394 public long getTotalPrefixesInstalled() {
395 return this.prefixesInstalled.values().stream().mapToLong(LongAdder::longValue).sum();