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 java.util.Objects.requireNonNull;
11 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ADJRIBIN_NID;
12 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ADJRIBOUT_NID;
13 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ATTRIBUTES_NID;
14 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.EFFRIBIN_NID;
15 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.TABLES_NID;
16 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.UPTODATE_NID;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.ImmutableMap.Builder;
21 import com.google.common.util.concurrent.FluentFuture;
22 import com.google.common.util.concurrent.FutureCallback;
23 import com.google.common.util.concurrent.MoreExecutors;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.List;
29 import java.util.Optional;
31 import java.util.concurrent.CountDownLatch;
32 import java.util.concurrent.ExecutionException;
33 import java.util.stream.Collectors;
34 import org.checkerframework.checker.lock.qual.GuardedBy;
35 import org.eclipse.jdt.annotation.NonNull;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.opendaylight.mdsal.common.api.CommitInfo;
38 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
39 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
40 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
41 import org.opendaylight.protocol.bgp.rib.impl.ApplicationPeer.RegisterAppPeerListener;
42 import org.opendaylight.protocol.bgp.rib.impl.spi.PeerTransactionChain;
43 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
44 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
45 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
46 import org.opendaylight.protocol.bgp.rib.spi.PeerRoleUtil;
47 import org.opendaylight.protocol.bgp.rib.spi.RIBNormalizedNodes;
48 import org.opendaylight.protocol.bgp.rib.spi.RIBQNames;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.SendReceive;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.attributes.reach.MpReachNlri;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.attributes.unreach.MpUnreachNlri;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerId;
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.bgp.rib.rib.Peer;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.SupportedTables;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
62 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
66 import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
71 * Writer of Adjacency-RIB-In for a single peer. An instance of this object is attached to each {@link BGPPeer} and
72 * {@link ApplicationPeer}. This class is NOT thread-safe.
74 final class AdjRibInWriter {
76 private static final Logger LOG = LoggerFactory.getLogger(AdjRibInWriter.class);
78 private static final QName PEER_ROLE_QNAME = QName.create(Peer.QNAME, "peer-role").intern();
79 private static final NodeIdentifier PEER_ID = NodeIdentifier.create(RIBQNames.PEER_ID_QNAME);
80 private static final NodeIdentifier PEER_ROLE = NodeIdentifier.create(PEER_ROLE_QNAME);
81 private static final NodeIdentifier PEER_TABLES = NodeIdentifier.create(SupportedTables.QNAME);
82 private static final QName SEND_RECEIVE = QName.create(SupportedTables.QNAME, "send-receive").intern();
84 // FIXME: is there a utility method to construct this?
85 private static final MapNode EMPTY_TABLES = ImmutableNodes.newSystemMapBuilder()
86 .withNodeIdentifier(TABLES_NID)
88 private static final ContainerNode EMPTY_ADJRIBIN = ImmutableNodes.newContainerBuilder()
89 .withNodeIdentifier(ADJRIBIN_NID).addChild(EMPTY_TABLES).build();
90 private static final ContainerNode EMPTY_EFFRIBIN = ImmutableNodes.newContainerBuilder()
91 .withNodeIdentifier(EFFRIBIN_NID).addChild(EMPTY_TABLES).build();
92 private static final ContainerNode EMPTY_ADJRIBOUT = ImmutableNodes.newContainerBuilder()
93 .withNodeIdentifier(ADJRIBOUT_NID).addChild(EMPTY_TABLES).build();
95 private final Map<TablesKey, TableContext> tables;
96 private final YangInstanceIdentifier ribPath;
97 private final PeerTransactionChain chain;
98 private final PeerRole role;
100 private final Map<TablesKey, Collection<NodeIdentifierWithPredicates>> staleRoutesRegistry = new HashMap<>();
102 private FluentFuture<? extends CommitInfo> submitted;
104 private AdjRibInWriter(final YangInstanceIdentifier ribPath, final PeerTransactionChain chain, final PeerRole role,
105 final Map<TablesKey, TableContext> tables) {
106 this.ribPath = requireNonNull(ribPath);
107 this.chain = requireNonNull(chain);
108 this.tables = requireNonNull(tables);
109 this.role = requireNonNull(role);
113 * Create a new writer using a transaction chain.
115 * @param role peer's role
116 * @param chain transaction chain @return A fresh writer instance
118 static AdjRibInWriter create(final @NonNull YangInstanceIdentifier ribId, final @NonNull PeerRole role,
119 final @NonNull PeerTransactionChain chain) {
120 return new AdjRibInWriter(ribId, chain, role, Collections.emptyMap());
124 * Transform this writer to a new writer, which is in charge of specified tables.
125 * Empty tables are created for new entries and old tables are deleted. Once this
126 * method returns, the old instance must not be reasonably used.
128 * @param newPeerId new peer BGP identifier
129 * @param peerPath path of the peer in the datastore
130 * @param registry RIB extension registry
131 * @param tableTypes New tables, must not be null
132 * @param addPathTablesType supported add path tables
135 AdjRibInWriter transform(final PeerId newPeerId, final YangInstanceIdentifier peerPath,
136 final RIBSupportContextRegistry registry,
137 final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType) {
138 return transform(newPeerId, peerPath, registry, tableTypes, addPathTablesType, null);
141 AdjRibInWriter transform(final PeerId newPeerId, final YangInstanceIdentifier peerPath,
142 final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes,
143 final Map<TablesKey, SendReceive> addPathTablesType,
144 final @Nullable RegisterAppPeerListener registerAppPeerListener) {
145 final DOMDataTreeWriteTransaction tx = chain.getDomChain().newWriteOnlyTransaction();
147 createEmptyPeerStructure(newPeerId, peerPath, tx);
148 final ImmutableMap<TablesKey, TableContext> tb = createNewTableInstances(peerPath, registry, tableTypes,
149 addPathTablesType, tx);
151 tx.commit().addCallback(new FutureCallback<CommitInfo>() {
153 public void onSuccess(final CommitInfo result) {
154 if (registerAppPeerListener != null) {
155 LOG.trace("Application Peer Listener registered");
156 registerAppPeerListener.register();
161 public void onFailure(final Throwable throwable) {
162 if (registerAppPeerListener != null) {
163 LOG.error("Failed to create Empty Structure, Application Peer Listener won't be registered",
166 LOG.error("Failed to create Empty Structure", throwable);
169 }, MoreExecutors.directExecutor());
170 return new AdjRibInWriter(ribPath, chain, role, tb);
174 * Create new table instances, potentially creating their empty entries.
176 private static ImmutableMap<TablesKey, TableContext> createNewTableInstances(
177 final YangInstanceIdentifier newPeerPath, final RIBSupportContextRegistry registry,
178 final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType,
179 final DOMDataTreeWriteTransaction tx) {
181 final Builder<TablesKey, TableContext> tb = ImmutableMap.builder();
182 for (final TablesKey tableKey : tableTypes) {
183 final RIBSupportContext rs = registry.getRIBSupportContext(tableKey);
185 LOG.warn("No support for table type {}, skipping it", tableKey);
188 installAdjRibsOutTables(newPeerPath, rs, addPathTablesType.get(tableKey), tx);
189 installAdjRibInTables(newPeerPath, tableKey, rs, tx, tb);
194 private static void installAdjRibInTables(final YangInstanceIdentifier newPeerPath, final TablesKey tableKey,
195 final RIBSupportContext rs, final DOMDataTreeWriteTransaction tx,
196 final Builder<TablesKey, TableContext> tb) {
197 // We will use table keys very often, make sure they are optimized
198 final InstanceIdentifierBuilder idb = YangInstanceIdentifier.builder(newPeerPath
199 .node(EMPTY_ADJRIBIN.name()).node(TABLES_NID)).node(rs.getRibSupport().tablesKey());
201 final TableContext ctx = new TableContext(rs, idb.build());
202 ctx.createEmptyTableStructure(tx);
204 tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(ATTRIBUTES_NID).node(UPTODATE_NID),
205 RIBNormalizedNodes.ATTRIBUTES_UPTODATE_FALSE);
206 LOG.debug("Created table instance {}", ctx.getTableId());
207 tb.put(tableKey, ctx);
210 private static void installAdjRibsOutTables(final YangInstanceIdentifier newPeerPath, final RIBSupportContext rs,
211 final SendReceive sendReceive, final DOMDataTreeWriteTransaction tx) {
212 final var tableKey = rs.getRibSupport().tablesKey();
213 final var supTablesKey = NodeIdentifierWithPredicates.of(SupportedTables.QNAME, tableKey.asMap());
214 final var tt = ImmutableNodes.newMapEntryBuilder().withNodeIdentifier(supTablesKey);
215 for (var e : supTablesKey.entrySet()) {
216 tt.withChild(ImmutableNodes.leafNode(e.getKey(), e.getValue()));
218 if (sendReceive != null) {
219 tt.withChild(ImmutableNodes.leafNode(SEND_RECEIVE, sendReceive.getName()));
221 tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath.node(PEER_TABLES).node(supTablesKey), tt.build());
222 rs.createEmptyTableStructure(tx,
223 newPeerPath.node(EMPTY_ADJRIBOUT.name()).node(TABLES_NID).node(tableKey));
226 private void createEmptyPeerStructure(final PeerId newPeerId,
227 final YangInstanceIdentifier peerPath, final DOMDataTreeWriteTransaction tx) {
228 final NodeIdentifierWithPredicates peerKey = IdentifierUtils.domPeerId(newPeerId);
230 tx.put(LogicalDatastoreType.OPERATIONAL, peerPath, peerSkeleton(peerKey, newPeerId.getValue()));
231 LOG.debug("New peer {} structure installed.", peerPath);
235 MapEntryNode peerSkeleton(final NodeIdentifierWithPredicates peerKey, final String peerId) {
236 return ImmutableNodes.newMapEntryBuilder()
237 .withNodeIdentifier(peerKey)
238 .withChild(ImmutableNodes.leafNode(PEER_ID, peerId))
239 .withChild(ImmutableNodes.leafNode(PEER_ROLE, PeerRoleUtil.roleForString(role)))
240 .withChild(ImmutableNodes.newSystemMapBuilder().withNodeIdentifier(PEER_TABLES).build())
241 .withChild(EMPTY_ADJRIBIN)
242 .withChild(EMPTY_EFFRIBIN)
243 .withChild(EMPTY_ADJRIBOUT)
247 void markTableUptodate(final TablesKey tableTypes) {
248 final DOMDataTreeWriteTransaction tx = chain.getDomChain().newWriteOnlyTransaction();
249 final TableContext ctx = tables.get(tableTypes);
250 tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(ATTRIBUTES_NID).node(UPTODATE_NID),
251 RIBNormalizedNodes.ATTRIBUTES_UPTODATE_TRUE);
252 tx.commit().addCallback(new FutureCallback<CommitInfo>() {
254 public void onSuccess(final CommitInfo result) {
255 LOG.trace("Write Attributes uptodate, succeed");
259 public void onFailure(final Throwable throwable) {
260 LOG.error("Write Attributes uptodate failed", throwable);
262 }, MoreExecutors.directExecutor());
265 void updateRoutes(final MpReachNlri nlri, final org.opendaylight.yang.gen.v1.urn.opendaylight.params
266 .xml.ns.yang.bgp.message.rev200120.path.attributes.Attributes attributes) {
267 final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
268 final TableContext ctx = tables.get(key);
270 LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
274 final DOMDataTreeWriteTransaction tx = chain.getDomChain().newWriteOnlyTransaction();
275 final Collection<NodeIdentifierWithPredicates> routeKeys = ctx.writeRoutes(tx, nlri, attributes);
276 final Collection<NodeIdentifierWithPredicates> staleRoutes = staleRoutesRegistry.get(key);
277 if (staleRoutes != null) {
278 staleRoutes.removeAll(routeKeys);
280 LOG.trace("Write routes {}", nlri);
281 final FluentFuture<? extends CommitInfo> future = tx.commit();
283 future.addCallback(new FutureCallback<CommitInfo>() {
285 public void onSuccess(final CommitInfo result) {
286 LOG.trace("Write routes {}, succeed", nlri);
290 public void onFailure(final Throwable throwable) {
291 LOG.error("Write routes failed", throwable);
293 }, MoreExecutors.directExecutor());
296 void removeRoutes(final MpUnreachNlri nlri) {
297 final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
298 final TableContext ctx = tables.get(key);
300 LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
303 LOG.trace("Removing routes {}", nlri);
304 final DOMDataTreeWriteTransaction tx = chain.getDomChain().newWriteOnlyTransaction();
305 ctx.removeRoutes(tx, nlri);
306 final FluentFuture<? extends CommitInfo> future = tx.commit();
308 future.addCallback(new FutureCallback<CommitInfo>() {
310 public void onSuccess(final CommitInfo result) {
311 LOG.trace("Removing routes {}, succeed", nlri);
315 public void onFailure(final Throwable throwable) {
316 LOG.error("Removing routes failed", throwable);
318 }, MoreExecutors.directExecutor());
321 void releaseChain() {
322 if (submitted != null) {
325 } catch (final InterruptedException | ExecutionException throwable) {
326 LOG.error("Write routes failed", throwable);
331 void storeStaleRoutes(final Set<TablesKey> gracefulTables) {
332 final CountDownLatch latch = new CountDownLatch(gracefulTables.size());
334 try (DOMDataTreeReadTransaction tx = chain.getDomChain().newReadOnlyTransaction()) {
335 for (TablesKey tablesKey : gracefulTables) {
336 final TableContext ctx = tables.get(tablesKey);
338 LOG.warn("Missing table for address family {}", tablesKey);
343 tx.read(LogicalDatastoreType.OPERATIONAL, ctx.routesPath()).addCallback(
344 new FutureCallback<Optional<NormalizedNode>>() {
346 public void onSuccess(final Optional<NormalizedNode> routesOptional) {
348 if (routesOptional.isPresent()) {
349 synchronized (staleRoutesRegistry) {
350 final MapNode routesNode = (MapNode) routesOptional.orElseThrow();
351 final List<NodeIdentifierWithPredicates> routes = routesNode.body().stream()
352 .map(MapEntryNode::name)
353 .collect(Collectors.toList());
354 if (!routes.isEmpty()) {
355 staleRoutesRegistry.put(tablesKey, routes);
365 public void onFailure(final Throwable throwable) {
366 LOG.warn("Failed to store stale routes for table {}", tablesKey, throwable);
369 }, MoreExecutors.directExecutor());
375 } catch (InterruptedException e) {
376 LOG.warn("Interrupted while waiting to store stale routes with {} tasks of {} to finish", latch.getCount(),
381 void removeStaleRoutes(final TablesKey tableKey) {
382 final TableContext ctx = tables.get(tableKey);
384 LOG.debug("No table for {}, not removing any stale routes", tableKey);
387 final Collection<NodeIdentifierWithPredicates> routeKeys = staleRoutesRegistry.get(tableKey);
388 if (routeKeys == null || routeKeys.isEmpty()) {
389 LOG.debug("No stale routes present in table {}", tableKey);
392 LOG.trace("Removing routes {}", routeKeys);
393 final DOMDataTreeWriteTransaction tx = chain.getDomChain().newWriteOnlyTransaction();
394 routeKeys.forEach(routeKey -> {
395 tx.delete(LogicalDatastoreType.OPERATIONAL, ctx.routePath(routeKey));
397 final FluentFuture<? extends CommitInfo> future = tx.commit();
399 future.addCallback(new FutureCallback<CommitInfo>() {
401 public void onSuccess(final CommitInfo result) {
402 LOG.trace("Removing routes {}, succeed", routeKeys);
403 synchronized (staleRoutesRegistry) {
404 staleRoutesRegistry.remove(tableKey);
409 public void onFailure(final Throwable throwable) {
410 LOG.warn("Removing routes {}, failed", routeKeys, throwable);
412 }, MoreExecutors.directExecutor());
415 FluentFuture<? extends CommitInfo> clearTables(final Set<TablesKey> tablesToClear) {
416 if (tablesToClear == null || tablesToClear.isEmpty()) {
417 return CommitInfo.emptyFluentFuture();
420 final DOMDataTreeWriteTransaction wtx = chain.getDomChain().newWriteOnlyTransaction();
421 tablesToClear.forEach(tableKey -> {
422 final TableContext ctx = tables.get(tableKey);
423 wtx.delete(LogicalDatastoreType.OPERATIONAL, ctx.routesPath().getParent());