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;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.ImmutableMap.Builder;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import com.google.common.util.concurrent.MoreExecutors;
19 import java.util.Collections;
20 import java.util.Locale;
22 import java.util.Map.Entry;
23 import java.util.Optional;
25 import javax.annotation.Nonnull;
26 import javax.annotation.Nullable;
27 import javax.annotation.concurrent.NotThreadSafe;
28 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
29 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
30 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
31 import org.opendaylight.protocol.bgp.rib.impl.ApplicationPeer.RegisterAppPeerListener;
32 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
33 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
34 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
35 import org.opendaylight.protocol.bgp.rib.spi.PeerRoleUtil;
36 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.SendReceive;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.update.attributes.MpReachNlri;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.update.attributes.MpUnreachNlri;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerId;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerRole;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.SimpleRoutingPolicy;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.Peer;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.peer.AdjRibIn;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.peer.AdjRibOut;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.peer.EffectiveRibIn;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.peer.SupportedTables;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.Tables;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.TablesKey;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.tables.Attributes;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
56 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
59 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
60 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
61 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
62 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
63 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
68 * Writer of Adjacency-RIB-In for a single peer. An instance of this object
69 * is attached to each {@link BGPPeer} and {@link ApplicationPeer}.
72 final class AdjRibInWriter {
74 private static final Logger LOG = LoggerFactory.getLogger(AdjRibInWriter.class);
77 static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_FALSE = ImmutableNodes.leafNode(QName.create(Attributes.QNAME,
78 "uptodate"), Boolean.FALSE);
80 static final QName PEER_ID_QNAME = QName.create(Peer.QNAME, "peer-id").intern();
81 private static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_TRUE =
82 ImmutableNodes.leafNode(ATTRIBUTES_UPTODATE_FALSE.getNodeType(), Boolean.TRUE);
83 private static final QName PEER_ROLE_QNAME = QName.create(Peer.QNAME, "peer-role").intern();
84 private static final NodeIdentifier ADJRIBIN = new NodeIdentifier(AdjRibIn.QNAME);
85 private static final NodeIdentifier ADJRIBOUT = new NodeIdentifier(AdjRibOut.QNAME);
86 private static final NodeIdentifier EFFRIBIN = new NodeIdentifier(EffectiveRibIn.QNAME);
87 private static final NodeIdentifier PEER_ID = new NodeIdentifier(PEER_ID_QNAME);
88 private static final NodeIdentifier PEER_ROLE = new NodeIdentifier(PEER_ROLE_QNAME);
89 private static final NodeIdentifier PEER_TABLES = new NodeIdentifier(SupportedTables.QNAME);
90 private static final NodeIdentifier TABLES = new NodeIdentifier(Tables.QNAME);
91 private static final QName SEND_RECEIVE = QName.create(SupportedTables.QNAME, "send-receive").intern();
92 private static final NodeIdentifier SIMPLE_ROUTING_POLICY_NID =
93 new NodeIdentifier(QName.create(Peer.QNAME, "simple-routing-policy").intern());
95 // FIXME: is there a utility method to construct this?
96 private static final ContainerNode EMPTY_ADJRIBIN = Builders.containerBuilder()
97 .withNodeIdentifier(ADJRIBIN).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
98 private static final ContainerNode EMPTY_EFFRIBIN = Builders.containerBuilder()
99 .withNodeIdentifier(EFFRIBIN).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
100 private static final ContainerNode EMPTY_ADJRIBOUT = Builders.containerBuilder()
101 .withNodeIdentifier(ADJRIBOUT).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
103 private final Map<TablesKey, TableContext> tables;
104 private final YangInstanceIdentifier peerPath;
105 private final YangInstanceIdentifier ribPath;
106 private final DOMTransactionChain chain;
107 private final PeerRole role;
108 private final Optional<SimpleRoutingPolicy> simpleRoutingPolicy;
110 private AdjRibInWriter(final YangInstanceIdentifier ribPath, final DOMTransactionChain chain, final PeerRole role,
111 final Optional<SimpleRoutingPolicy> simpleRoutingPolicy, final YangInstanceIdentifier peerPath,
112 final Map<TablesKey, TableContext> tables) {
113 this.ribPath = requireNonNull(ribPath);
114 this.chain = requireNonNull(chain);
115 this.tables = requireNonNull(tables);
116 this.role = requireNonNull(role);
117 this.simpleRoutingPolicy = simpleRoutingPolicy;
118 this.peerPath = peerPath;
122 * Create a new writer using a transaction chain.
124 * @param role peer's role
125 * @param simpleRoutingPolicy simple Routing Policy {@link SimpleRoutingPolicy}
126 * @param chain transaction chain @return A fresh writer instance
128 static AdjRibInWriter create(@Nonnull final YangInstanceIdentifier ribId, @Nonnull final PeerRole role,
129 final Optional<SimpleRoutingPolicy> simpleRoutingPolicy, @Nonnull final DOMTransactionChain chain) {
130 return new AdjRibInWriter(ribId, chain, role, simpleRoutingPolicy, null, Collections.emptyMap());
134 * Transform this writer to a new writer, which is in charge of specified tables.
135 * Empty tables are created for new entries and old tables are deleted. Once this
136 * method returns, the old instance must not be reasonably used.
138 * @param newPeerId new peer BGP identifier
139 * @param registry RIB extension registry
140 * @param tableTypes New tables, must not be null
141 * @param addPathTablesType
144 AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry,
145 final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType) {
146 return transform(newPeerId, registry, tableTypes, addPathTablesType, null);
149 AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry,
150 final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType,
151 @Nullable final RegisterAppPeerListener registerAppPeerListener) {
152 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
154 final YangInstanceIdentifier newPeerPath;
155 newPeerPath = createEmptyPeerStructure(newPeerId, tx);
156 final ImmutableMap<TablesKey, TableContext> tb = createNewTableInstances(newPeerPath, registry, tableTypes,
157 addPathTablesType, tx);
159 Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
161 public void onSuccess(final Void result) {
162 if (registerAppPeerListener != null) {
163 LOG.trace("Application Peer Listener registered");
164 registerAppPeerListener.register();
169 public void onFailure(final Throwable throwable) {
170 if (registerAppPeerListener != null) {
171 LOG.error("Failed to create Empty Structure, Application Peer Listener won't be registered",
174 LOG.error("Failed to create Empty Structure", throwable);
177 }, MoreExecutors.directExecutor());
178 return new AdjRibInWriter(this.ribPath, this.chain, this.role, this.simpleRoutingPolicy, newPeerPath, tb);
182 * Create new table instances, potentially creating their empty entries
184 private ImmutableMap<TablesKey, TableContext> createNewTableInstances(final YangInstanceIdentifier newPeerPath,
185 final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes,
186 final Map<TablesKey, SendReceive> addPathTablesType, final DOMDataWriteTransaction tx) {
188 final Builder<TablesKey, TableContext> tb = ImmutableMap.builder();
189 for (final TablesKey tableKey : tableTypes) {
190 final RIBSupportContext rs = registry.getRIBSupportContext(tableKey);
191 // TODO: Use returned value once Instance Identifier builder allows for it.
192 final NodeIdentifierWithPredicates instanceIdentifierKey = RibSupportUtils.toYangTablesKey(tableKey);
194 LOG.warn("No support for table type {}, skipping it", tableKey);
197 installAdjRibsOutTables(newPeerPath, rs, instanceIdentifierKey, tableKey, addPathTablesType.get(tableKey), tx);
198 installAdjRibInTables(newPeerPath, tableKey, rs, instanceIdentifierKey, tx, tb);
203 private static void installAdjRibInTables(final YangInstanceIdentifier newPeerPath, final TablesKey tableKey,
204 final RIBSupportContext rs, final NodeIdentifierWithPredicates instanceIdentifierKey,
205 final DOMDataWriteTransaction tx, final Builder<TablesKey, TableContext> tb) {
206 // We will use table keys very often, make sure they are optimized
207 final InstanceIdentifierBuilder idb = YangInstanceIdentifier.builder(newPeerPath
208 .node(EMPTY_ADJRIBIN.getIdentifier()).node(TABLES));
209 idb.nodeWithKey(instanceIdentifierKey.getNodeType(), instanceIdentifierKey.getKeyValues());
211 final TableContext ctx = new TableContext(rs, idb.build());
212 ctx.createEmptyTableStructure(tx);
214 tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(Attributes.QNAME)
215 .node(ATTRIBUTES_UPTODATE_FALSE.getNodeType()), ATTRIBUTES_UPTODATE_FALSE);
216 LOG.debug("Created table instance {}", ctx.getTableId());
217 tb.put(tableKey, ctx);
220 private void installAdjRibsOutTables(final YangInstanceIdentifier newPeerPath, final RIBSupportContext rs,
221 final NodeIdentifierWithPredicates instanceIdentifierKey, final TablesKey tableKey,
222 final SendReceive sendReceive, final DOMDataWriteTransaction tx) {
223 if (!isAnnounceNone(this.simpleRoutingPolicy)) {
224 final NodeIdentifierWithPredicates supTablesKey = RibSupportUtils.toYangKey(SupportedTables.QNAME, tableKey);
225 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> tt =
226 Builders.mapEntryBuilder().withNodeIdentifier(supTablesKey);
227 for (final Entry<QName, Object> e : supTablesKey.getKeyValues().entrySet()) {
228 tt.withChild(ImmutableNodes.leafNode(e.getKey(), e.getValue()));
230 if (sendReceive != null) {
231 tt.withChild(ImmutableNodes.leafNode(SEND_RECEIVE, sendReceive.toString().toLowerCase(Locale.ENGLISH)));
233 tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath.node(PEER_TABLES).node(supTablesKey), tt.build());
234 rs.createEmptyTableStructure(tx, newPeerPath.node(EMPTY_ADJRIBOUT.getIdentifier())
235 .node(TABLES).node(instanceIdentifierKey));
239 private YangInstanceIdentifier createEmptyPeerStructure(final PeerId newPeerId, final DOMDataWriteTransaction tx) {
240 final NodeIdentifierWithPredicates peerKey = IdentifierUtils.domPeerId(newPeerId);
241 final YangInstanceIdentifier newPeerPath = this.ribPath.node(Peer.QNAME).node(peerKey);
243 tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath, peerSkeleton(peerKey, newPeerId.getValue()));
244 LOG.debug("New peer {} structure installed.", newPeerPath);
249 MapEntryNode peerSkeleton(final NodeIdentifierWithPredicates peerKey, final String peerId) {
250 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> pb = Builders.mapEntryBuilder();
251 pb.withNodeIdentifier(peerKey);
252 pb.withChild(ImmutableNodes.leafNode(PEER_ID, peerId));
253 pb.withChild(ImmutableNodes.leafNode(PEER_ROLE, PeerRoleUtil.roleForString(this.role)));
254 if (this.simpleRoutingPolicy.isPresent() && this.role != PeerRole.Internal) {
255 pb.withChild(ImmutableNodes.leafNode(SIMPLE_ROUTING_POLICY_NID,
256 simpleRoutingPolicyString(this.simpleRoutingPolicy.get())));
258 pb.withChild(ImmutableMapNodeBuilder.create().withNodeIdentifier(PEER_TABLES).build());
259 pb.withChild(EMPTY_ADJRIBIN);
260 if (!isLearnNone(this.simpleRoutingPolicy)) {
261 pb.withChild(EMPTY_EFFRIBIN);
263 if (!isAnnounceNone(this.simpleRoutingPolicy)) {
264 pb.withChild(EMPTY_ADJRIBOUT);
269 synchronized ListenableFuture<Void> removePeer() {
270 if (this.peerPath != null) {
272 LOG.info("AdjRibInWriter closed per Peer {} removed", AdjRibInWriter.this.peerPath);
273 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
274 tx.delete(LogicalDatastoreType.OPERATIONAL, this.peerPath);
275 final ListenableFuture<Void> future = tx.submit();
276 Futures.addCallback(future, new FutureCallback<Void>() {
278 public void onSuccess(final Void result) {
279 LOG.debug("Peer {} removed", AdjRibInWriter.this.peerPath);
283 public void onFailure(final Throwable t) {
284 LOG.warn("Failed to remove Peer {}", AdjRibInWriter.this.peerPath, t);
286 }, MoreExecutors.directExecutor());
289 return Futures.immediateFuture(null);
292 void markTableUptodate(final TablesKey tableTypes) {
293 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
294 final TableContext ctx = this.tables.get(tableTypes);
295 tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(Attributes.QNAME)
296 .node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
300 void updateRoutes(final MpReachNlri nlri, final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang
301 .bgp.message.rev171207.path.attributes.Attributes attributes) {
302 final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
303 final TableContext ctx = this.tables.get(key);
305 LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
309 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
310 ctx.writeRoutes(tx, nlri, attributes);
311 LOG.trace("Write routes {}", nlri);
315 void removeRoutes(final MpUnreachNlri nlri) {
316 final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
317 final TableContext ctx = this.tables.get(key);
319 LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
322 LOG.trace("Removing routes {}", nlri);
323 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
324 ctx.removeRoutes(tx, nlri);
328 static boolean isAnnounceNone(final java.util.Optional<SimpleRoutingPolicy> peerStatus) {
329 return peerStatus.isPresent() && peerStatus.get() == SimpleRoutingPolicy.AnnounceNone;
332 static boolean isLearnNone(final java.util.Optional<SimpleRoutingPolicy> peerStatus) {
333 return peerStatus.isPresent() && peerStatus.get() == SimpleRoutingPolicy.LearnNone;
336 private static String simpleRoutingPolicyString(final SimpleRoutingPolicy simpleRoutingPolicy) {
337 switch (simpleRoutingPolicy) {
339 return "announce-none";
343 throw new IllegalArgumentException("Unhandled Simple Routing Policy " + simpleRoutingPolicy);