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;
21 import java.util.Map.Entry;
22 import java.util.Optional;
24 import javax.annotation.Nonnull;
25 import javax.annotation.Nullable;
26 import javax.annotation.concurrent.NotThreadSafe;
27 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
29 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
30 import org.opendaylight.protocol.bgp.rib.impl.ApplicationPeer.RegisterAppPeerListener;
31 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
32 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
33 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
34 import org.opendaylight.protocol.bgp.rib.spi.PeerRoleUtil;
35 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.SendReceive;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.update.attributes.MpReachNlri;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.update.attributes.MpUnreachNlri;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerId;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerRole;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.SimpleRoutingPolicy;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.Peer;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.peer.AdjRibIn;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.peer.AdjRibOut;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.peer.EffectiveRibIn;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.peer.SupportedTables;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.Tables;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.TablesKey;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.tables.Attributes;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
55 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
58 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
59 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
60 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
61 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
62 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
67 * Writer of Adjacency-RIB-In for a single peer. An instance of this object
68 * is attached to each {@link BGPPeer} and {@link ApplicationPeer}.
71 final class AdjRibInWriter {
73 private static final Logger LOG = LoggerFactory.getLogger(AdjRibInWriter.class);
76 static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_FALSE = ImmutableNodes.leafNode(QName.create(Attributes.QNAME, "uptodate"), Boolean.FALSE);
78 static final QName PEER_ID_QNAME = QName.create(Peer.QNAME, "peer-id").intern();
79 private static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_TRUE = ImmutableNodes.leafNode(ATTRIBUTES_UPTODATE_FALSE.getNodeType(), Boolean.TRUE);
80 private static final QName PEER_ROLE_QNAME = QName.create(Peer.QNAME, "peer-role").intern();
81 private static final NodeIdentifier ADJRIBIN = new NodeIdentifier(AdjRibIn.QNAME);
82 private static final NodeIdentifier ADJRIBOUT = new NodeIdentifier(AdjRibOut.QNAME);
83 private static final NodeIdentifier EFFRIBIN = new NodeIdentifier(EffectiveRibIn.QNAME);
84 private static final NodeIdentifier PEER_ID = new NodeIdentifier(PEER_ID_QNAME);
85 private static final NodeIdentifier PEER_ROLE = new NodeIdentifier(PEER_ROLE_QNAME);
86 private static final NodeIdentifier PEER_TABLES = new NodeIdentifier(SupportedTables.QNAME);
87 private static final NodeIdentifier TABLES = new NodeIdentifier(Tables.QNAME);
88 private static final QName SEND_RECEIVE = QName.create(SupportedTables.QNAME, "send-receive").intern();
89 private static final NodeIdentifier SIMPLE_ROUTING_POLICY_NID = new NodeIdentifier(QName.create(Peer.QNAME, "simple-routing-policy").intern());
91 // FIXME: is there a utility method to construct this?
92 private static final ContainerNode EMPTY_ADJRIBIN = Builders.containerBuilder().withNodeIdentifier(ADJRIBIN).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
93 private static final ContainerNode EMPTY_EFFRIBIN = Builders.containerBuilder().withNodeIdentifier(EFFRIBIN).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
94 private static final ContainerNode EMPTY_ADJRIBOUT = Builders.containerBuilder().withNodeIdentifier(ADJRIBOUT).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
96 private final Map<TablesKey, TableContext> tables;
97 private final YangInstanceIdentifier peerPath;
98 private final YangInstanceIdentifier ribPath;
99 private final DOMTransactionChain chain;
100 private final PeerRole role;
101 private final Optional<SimpleRoutingPolicy> simpleRoutingPolicy;
103 private AdjRibInWriter(final YangInstanceIdentifier ribPath, final DOMTransactionChain chain, final PeerRole role,
104 final Optional<SimpleRoutingPolicy> simpleRoutingPolicy, final YangInstanceIdentifier peerPath,
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);
110 this.simpleRoutingPolicy = simpleRoutingPolicy;
111 this.peerPath = peerPath;
115 * Create a new writer using a transaction chain.
117 * @param role peer's role
118 * @param simpleRoutingPolicy simple Routing Policy {@link SimpleRoutingPolicy}
119 * @param chain transaction chain @return A fresh writer instance
121 static AdjRibInWriter create(@Nonnull final YangInstanceIdentifier ribId, @Nonnull final PeerRole role,
122 final Optional<SimpleRoutingPolicy> simpleRoutingPolicy, @Nonnull final DOMTransactionChain chain) {
123 return new AdjRibInWriter(ribId, chain, role, simpleRoutingPolicy, null, Collections.emptyMap());
127 * Transform this writer to a new writer, which is in charge of specified tables.
128 * Empty tables are created for new entries and old tables are deleted. Once this
129 * method returns, the old instance must not be reasonably used.
131 * @param newPeerId new peer BGP identifier
132 * @param registry RIB extension registry
133 * @param tableTypes New tables, must not be null
134 * @param addPathTablesType
137 AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry,
138 final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType) {
139 return transform(newPeerId, registry, tableTypes, addPathTablesType, null);
142 AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes,
143 final Map<TablesKey, SendReceive> addPathTablesType, @Nullable final RegisterAppPeerListener registerAppPeerListener) {
144 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
146 final YangInstanceIdentifier newPeerPath;
147 newPeerPath = createEmptyPeerStructure(newPeerId, tx);
148 final ImmutableMap<TablesKey, TableContext> tb = createNewTableInstances(newPeerPath, registry, tableTypes,
149 addPathTablesType, tx);
151 Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
153 public void onSuccess(final Void 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(this.ribPath, this.chain, this.role, this.simpleRoutingPolicy, newPeerPath, tb);
174 * Create new table instances, potentially creating their empty entries
179 * @param addPathTablesType
183 private ImmutableMap<TablesKey, TableContext> createNewTableInstances(final YangInstanceIdentifier newPeerPath,
184 final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType,
185 final DOMDataWriteTransaction tx) {
187 final Builder<TablesKey, TableContext> tb = ImmutableMap.builder();
188 for (final TablesKey tableKey : tableTypes) {
189 final RIBSupportContext rs = registry.getRIBSupportContext(tableKey);
190 // TODO: Use returned value once Instance Identifier builder allows for it.
191 final NodeIdentifierWithPredicates instanceIdentifierKey = RibSupportUtils.toYangTablesKey(tableKey);
193 LOG.warn("No support for table type {}, skipping it", tableKey);
196 installAdjRibsOutTables(newPeerPath, rs, instanceIdentifierKey, tableKey, addPathTablesType.get(tableKey), tx);
197 installAdjRibInTables(newPeerPath, tableKey, rs, instanceIdentifierKey, tx, tb);
202 private static void installAdjRibInTables(final YangInstanceIdentifier newPeerPath, final TablesKey tableKey,
203 final RIBSupportContext rs, final NodeIdentifierWithPredicates instanceIdentifierKey,
204 final DOMDataWriteTransaction tx, final Builder<TablesKey, TableContext> tb) {
205 // We will use table keys very often, make sure they are optimized
206 final InstanceIdentifierBuilder idb = YangInstanceIdentifier.builder(newPeerPath.node(EMPTY_ADJRIBIN.getIdentifier()).node(TABLES));
207 idb.nodeWithKey(instanceIdentifierKey.getNodeType(), instanceIdentifierKey.getKeyValues());
209 final TableContext ctx = new TableContext(rs, idb.build());
210 ctx.createEmptyTableStructure(tx);
212 tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_FALSE.getNodeType()), ATTRIBUTES_UPTODATE_FALSE);
213 LOG.debug("Created table instance {}", ctx.getTableId());
214 tb.put(tableKey, ctx);
217 private void installAdjRibsOutTables(final YangInstanceIdentifier newPeerPath, final RIBSupportContext rs,
218 final NodeIdentifierWithPredicates instanceIdentifierKey, final TablesKey tableKey, final SendReceive sendReceive,
219 final DOMDataWriteTransaction tx) {
220 if (!isAnnounceNone(this.simpleRoutingPolicy)) {
221 final NodeIdentifierWithPredicates supTablesKey = RibSupportUtils.toYangKey(SupportedTables.QNAME, tableKey);
222 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> tt = Builders.mapEntryBuilder().withNodeIdentifier(supTablesKey);
223 for (final Entry<QName, Object> e : supTablesKey.getKeyValues().entrySet()) {
224 tt.withChild(ImmutableNodes.leafNode(e.getKey(), e.getValue()));
226 if (sendReceive != null) {
227 tt.withChild(ImmutableNodes.leafNode(SEND_RECEIVE, sendReceive.toString().toLowerCase()));
229 tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath.node(PEER_TABLES).node(supTablesKey), tt.build());
230 rs.createEmptyTableStructure(tx, newPeerPath.node(EMPTY_ADJRIBOUT.getIdentifier()).node(TABLES).node(instanceIdentifierKey));
234 private YangInstanceIdentifier createEmptyPeerStructure(final PeerId newPeerId, final DOMDataWriteTransaction tx) {
235 final NodeIdentifierWithPredicates peerKey = IdentifierUtils.domPeerId(newPeerId);
236 final YangInstanceIdentifier newPeerPath = this.ribPath.node(Peer.QNAME).node(peerKey);
238 tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath, peerSkeleton(peerKey, newPeerId.getValue()));
239 LOG.debug("New peer {} structure installed.", newPeerPath);
244 MapEntryNode peerSkeleton(final NodeIdentifierWithPredicates peerKey, final String peerId) {
245 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> pb = Builders.mapEntryBuilder();
246 pb.withNodeIdentifier(peerKey);
247 pb.withChild(ImmutableNodes.leafNode(PEER_ID, peerId));
248 pb.withChild(ImmutableNodes.leafNode(PEER_ROLE, PeerRoleUtil.roleForString(this.role)));
249 if (this.simpleRoutingPolicy.isPresent() && this.role != PeerRole.Internal) {
250 pb.withChild(ImmutableNodes.leafNode(SIMPLE_ROUTING_POLICY_NID, simpleRoutingPolicyString(this.simpleRoutingPolicy.get())));
252 pb.withChild(ImmutableMapNodeBuilder.create().withNodeIdentifier(PEER_TABLES).build());
253 pb.withChild(EMPTY_ADJRIBIN);
254 if (!isLearnNone(this.simpleRoutingPolicy)) {
255 pb.withChild(EMPTY_EFFRIBIN);
257 if (!isAnnounceNone(this.simpleRoutingPolicy)) {
258 pb.withChild(EMPTY_ADJRIBOUT);
263 synchronized ListenableFuture<Void> removePeer() {
264 if (this.peerPath != null) {
266 LOG.info("AdjRibInWriter closed per Peer {} removed", AdjRibInWriter.this.peerPath);
267 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
268 tx.delete(LogicalDatastoreType.OPERATIONAL, this.peerPath);
269 final ListenableFuture<Void> future = tx.submit();
270 Futures.addCallback(future, new FutureCallback<Void>() {
272 public void onSuccess(final Void result) {
273 LOG.debug("Peer {} removed", AdjRibInWriter.this.peerPath);
277 public void onFailure(final Throwable t) {
278 LOG.warn("Failed to remove Peer {}", AdjRibInWriter.this.peerPath, t);
280 }, MoreExecutors.directExecutor());
283 return Futures.immediateFuture(null);
286 void markTableUptodate(final TablesKey tableTypes) {
287 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
288 final TableContext ctx = this.tables.get(tableTypes);
289 tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
293 void updateRoutes(final MpReachNlri nlri, final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.path.attributes.Attributes attributes) {
294 final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
295 final TableContext ctx = this.tables.get(key);
297 LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
301 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
302 ctx.writeRoutes(tx, nlri, attributes);
303 LOG.trace("Write routes {}", nlri);
307 void removeRoutes(final MpUnreachNlri nlri) {
308 final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
309 final TableContext ctx = this.tables.get(key);
311 LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
314 LOG.trace("Removing routes {}", nlri);
315 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
316 ctx.removeRoutes(tx, nlri);
320 static boolean isAnnounceNone(final java.util.Optional<SimpleRoutingPolicy> peerStatus) {
321 return peerStatus.isPresent() && peerStatus.get() == SimpleRoutingPolicy.AnnounceNone;
324 static boolean isLearnNone(final java.util.Optional<SimpleRoutingPolicy> peerStatus) {
325 return peerStatus.isPresent() && peerStatus.get() == SimpleRoutingPolicy.LearnNone;
328 private static String simpleRoutingPolicyString(final SimpleRoutingPolicy simpleRoutingPolicy) {
329 switch (simpleRoutingPolicy) {
331 return "announce-none";
335 throw new IllegalArgumentException("Unhandled Simple Routing Policy " + simpleRoutingPolicy);