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 com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.ImmutableMap.Builder;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import java.util.Collections;
18 import java.util.Map.Entry;
19 import java.util.Optional;
21 import javax.annotation.Nonnull;
22 import javax.annotation.Nullable;
23 import javax.annotation.concurrent.NotThreadSafe;
24 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
25 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
27 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
28 import org.opendaylight.protocol.bgp.rib.impl.ApplicationPeer.RegisterAppPeerListener;
29 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
30 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
31 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
32 import org.opendaylight.protocol.bgp.rib.spi.PeerRoleUtil;
33 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.SendReceive;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlri;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlri;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.SimpleRoutingPolicy;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibIn;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibOut;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.EffectiveRibIn;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.SupportedTables;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Attributes;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
53 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
56 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
57 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
58 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
59 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
60 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 * Writer of Adjacency-RIB-In for a single peer. An instance of this object
65 * is attached to each {@link BGPPeer} and {@link ApplicationPeer}.
68 final class AdjRibInWriter {
69 private static final Logger LOG = LoggerFactory.getLogger(AdjRibInWriter.class);
71 static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_FALSE = ImmutableNodes.leafNode(QName.create(Attributes.QNAME, "uptodate"), Boolean.FALSE);
72 private static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_TRUE = ImmutableNodes.leafNode(ATTRIBUTES_UPTODATE_FALSE.getNodeType(), Boolean.TRUE);
74 static final QName PEER_ID_QNAME = QName.create(Peer.QNAME, "peer-id").intern();
75 private static final QName PEER_ROLE_QNAME = QName.create(Peer.QNAME, "peer-role").intern();
76 private static final NodeIdentifier ADJRIBIN = new NodeIdentifier(AdjRibIn.QNAME);
77 private static final NodeIdentifier ADJRIBOUT = new NodeIdentifier(AdjRibOut.QNAME);
78 private static final NodeIdentifier EFFRIBIN = new NodeIdentifier(EffectiveRibIn.QNAME);
79 private static final NodeIdentifier PEER_ID = new NodeIdentifier(PEER_ID_QNAME);
80 private static final NodeIdentifier PEER_ROLE = new NodeIdentifier(PEER_ROLE_QNAME);
81 private static final NodeIdentifier PEER_TABLES = new NodeIdentifier(SupportedTables.QNAME);
82 private static final NodeIdentifier TABLES = new NodeIdentifier(Tables.QNAME);
83 private static final QName SEND_RECEIVE = QName.create(SupportedTables.QNAME, "send-receive").intern();
84 private static final NodeIdentifier SIMPLE_ROUTING_POLICY_NID = new NodeIdentifier(QName.create(Peer.QNAME, "simple-routing-policy").intern());
86 // FIXME: is there a utility method to construct this?
87 private static final ContainerNode EMPTY_ADJRIBIN = Builders.containerBuilder().withNodeIdentifier(ADJRIBIN).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
88 private static final ContainerNode EMPTY_EFFRIBIN = Builders.containerBuilder().withNodeIdentifier(EFFRIBIN).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
89 private static final ContainerNode EMPTY_ADJRIBOUT = Builders.containerBuilder().withNodeIdentifier(ADJRIBOUT).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
91 private final Map<TablesKey, TableContext> tables;
92 private final YangInstanceIdentifier peerPath;
93 private final YangInstanceIdentifier ribPath;
94 private final DOMTransactionChain chain;
95 private final PeerRole role;
96 private final Optional<SimpleRoutingPolicy> simpleRoutingPolicy;
98 private AdjRibInWriter(final YangInstanceIdentifier ribPath, final DOMTransactionChain chain, final PeerRole role,
99 final Optional<SimpleRoutingPolicy> simpleRoutingPolicy, final YangInstanceIdentifier peerPath, final Map<TablesKey, TableContext> tables) {
100 this.ribPath = Preconditions.checkNotNull(ribPath);
101 this.chain = Preconditions.checkNotNull(chain);
102 this.tables = Preconditions.checkNotNull(tables);
103 this.role = Preconditions.checkNotNull(role);
104 this.simpleRoutingPolicy = simpleRoutingPolicy;
105 this.peerPath = peerPath;
109 * Create a new writer using a transaction chain.
111 * @param role peer's role
112 * @param simpleRoutingPolicy simple Routing Policy {@link SimpleRoutingPolicy}
113 *@param chain transaction chain @return A fresh writer instance
115 static AdjRibInWriter create(@Nonnull final YangInstanceIdentifier ribId, @Nonnull final PeerRole role,
116 final Optional<SimpleRoutingPolicy> simpleRoutingPolicy, @Nonnull final DOMTransactionChain chain) {
117 return new AdjRibInWriter(ribId, chain, role, simpleRoutingPolicy, null, Collections.emptyMap());
121 * Transform this writer to a new writer, which is in charge of specified tables.
122 * Empty tables are created for new entries and old tables are deleted. Once this
123 * method returns, the old instance must not be reasonably used.
125 * @param newPeerId new peer BGP identifier
126 * @param registry RIB extension registry
127 * @param tableTypes New tables, must not be null
128 * @param addPathTablesType
131 AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry,
132 final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType) {
133 return transform(newPeerId, registry, tableTypes, addPathTablesType, null);
136 AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes,
137 final Map<TablesKey, SendReceive> addPathTablesType, @Nullable final RegisterAppPeerListener registerAppPeerListener) {
138 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
140 final YangInstanceIdentifier newPeerPath;
141 newPeerPath = createEmptyPeerStructure(newPeerId, tx);
142 final ImmutableMap<TablesKey, TableContext> tb = createNewTableInstances(newPeerPath, registry, tableTypes,
143 addPathTablesType, tx);
145 Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
147 public void onSuccess(final Void result) {
148 if(registerAppPeerListener != null) {
149 LOG.trace("Application Peer Listener registered");
150 registerAppPeerListener.register();
155 public void onFailure(final Throwable throwable) {
156 if(registerAppPeerListener != null) {
157 LOG.error("Failed to create Empty Structure, Application Peer Listener won't be registered",
160 LOG.error("Failed to create Empty Structure", throwable);
164 return new AdjRibInWriter(this.ribPath, this.chain, this.role, this.simpleRoutingPolicy, newPeerPath, tb);
168 * Create new table instances, potentially creating their empty entries
172 * @param addPathTablesType
176 private ImmutableMap<TablesKey, TableContext> createNewTableInstances(final YangInstanceIdentifier newPeerPath,
177 final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType,
178 final DOMDataWriteTransaction tx) {
180 final Builder<TablesKey, TableContext> tb = ImmutableMap.builder();
181 for (final TablesKey tableKey : tableTypes) {
182 final RIBSupportContext rs = registry.getRIBSupportContext(tableKey);
183 // TODO: Use returned value once Instance Identifier builder allows for it.
184 final NodeIdentifierWithPredicates instanceIdentifierKey = RibSupportUtils.toYangTablesKey(tableKey);
186 LOG.warn("No support for table type {}, skipping it", tableKey);
189 installAdjRibsOutTables(newPeerPath, rs, instanceIdentifierKey, tableKey, addPathTablesType.get(tableKey), tx);
190 installAdjRibInTables(newPeerPath, tableKey, rs, instanceIdentifierKey, tx, tb);
195 private void installAdjRibInTables(final YangInstanceIdentifier newPeerPath, final TablesKey tableKey, final RIBSupportContext rs,
196 final NodeIdentifierWithPredicates instanceIdentifierKey, final DOMDataWriteTransaction tx, 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.node(EMPTY_ADJRIBIN.getIdentifier()).node(TABLES));
199 idb.nodeWithKey(instanceIdentifierKey.getNodeType(), instanceIdentifierKey.getKeyValues());
201 final TableContext ctx = new TableContext(rs, idb.build());
202 ctx.createEmptyTableStructure(tx);
204 tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_FALSE.getNodeType()), ATTRIBUTES_UPTODATE_FALSE);
205 LOG.debug("Created table instance {}", ctx.getTableId());
206 tb.put(tableKey, ctx);
209 private void installAdjRibsOutTables(final YangInstanceIdentifier newPeerPath, final RIBSupportContext rs,
210 final NodeIdentifierWithPredicates instanceIdentifierKey, final TablesKey tableKey, final SendReceive sendReceive,
211 final DOMDataWriteTransaction tx) {
212 if (!isAnnounceNone(this.simpleRoutingPolicy)) {
213 final NodeIdentifierWithPredicates supTablesKey = RibSupportUtils.toYangKey(SupportedTables.QNAME, tableKey);
214 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> tt = Builders.mapEntryBuilder().withNodeIdentifier(supTablesKey);
215 for (final Entry<QName, Object> e : supTablesKey.getKeyValues().entrySet()) {
216 tt.withChild(ImmutableNodes.leafNode(e.getKey(), e.getValue()));
218 if(sendReceive != null) {
219 tt.withChild(ImmutableNodes.leafNode(SEND_RECEIVE, sendReceive.toString().toLowerCase()));
221 tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath.node(PEER_TABLES).node(supTablesKey), tt.build());
222 rs.createEmptyTableStructure(tx, newPeerPath.node(EMPTY_ADJRIBOUT.getIdentifier()).node(TABLES).node(instanceIdentifierKey));
226 private YangInstanceIdentifier createEmptyPeerStructure(final PeerId newPeerId, final DOMDataWriteTransaction tx) {
227 final NodeIdentifierWithPredicates peerKey = IdentifierUtils.domPeerId(newPeerId);
228 final YangInstanceIdentifier newPeerPath = this.ribPath.node(Peer.QNAME).node(peerKey);
230 tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath, peerSkeleton(peerKey, newPeerId.getValue()));
231 LOG.debug("New peer {} structure installed.", newPeerPath);
236 MapEntryNode peerSkeleton(final NodeIdentifierWithPredicates peerKey, final String peerId) {
237 final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> pb = Builders.mapEntryBuilder();
238 pb.withNodeIdentifier(peerKey);
239 pb.withChild(ImmutableNodes.leafNode(PEER_ID, peerId));
240 pb.withChild(ImmutableNodes.leafNode(PEER_ROLE, PeerRoleUtil.roleForString(this.role)));
241 if (this.simpleRoutingPolicy.isPresent() && this.role != PeerRole.Internal) {
242 pb.withChild(ImmutableNodes.leafNode(SIMPLE_ROUTING_POLICY_NID, simpleRoutingPolicyString(this.simpleRoutingPolicy.get())));
244 pb.withChild(ImmutableMapNodeBuilder.create().withNodeIdentifier(PEER_TABLES).build());
245 pb.withChild(EMPTY_ADJRIBIN);
246 if(!isLearnNone(this.simpleRoutingPolicy)) {
247 pb.withChild(EMPTY_EFFRIBIN);
249 if (!isAnnounceNone(this.simpleRoutingPolicy)) {
250 pb.withChild(EMPTY_ADJRIBOUT);
256 if(this.peerPath != null) {
257 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
258 tx.delete(LogicalDatastoreType.OPERATIONAL, this.peerPath);
261 tx.submit().checkedGet();
262 } catch (final TransactionCommitFailedException e) {
263 LOG.debug("Failed to remove Peer {}", this.peerPath, e);
268 void markTableUptodate(final TablesKey tableTypes) {
269 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
270 final TableContext ctx = this.tables.get(tableTypes);
271 tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
275 void updateRoutes(final MpReachNlri nlri, final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.Attributes attributes) {
276 final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
277 final TableContext ctx = this.tables.get(key);
279 LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
283 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
284 ctx.writeRoutes(tx, nlri, attributes);
285 LOG.trace("Write routes {}", nlri);
289 void removeRoutes(final MpUnreachNlri nlri) {
290 final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
291 final TableContext ctx = this.tables.get(key);
293 LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
296 LOG.trace("Removing routes {}", nlri);
297 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
298 ctx.removeRoutes(tx, nlri);
302 static boolean isAnnounceNone(final java.util.Optional<SimpleRoutingPolicy> peerStatus) {
303 return peerStatus.isPresent() && peerStatus.get() == SimpleRoutingPolicy.AnnounceNone;
306 static boolean isLearnNone(final java.util.Optional<SimpleRoutingPolicy> peerStatus) {
307 return peerStatus.isPresent() && peerStatus.get() == SimpleRoutingPolicy.LearnNone;
310 private static String simpleRoutingPolicyString(final SimpleRoutingPolicy simpleRoutingPolicy) {
311 switch (simpleRoutingPolicy) {
313 return "announce-none";
317 throw new IllegalArgumentException("Unhandled Simple Routing Policy " + simpleRoutingPolicy);