Provide Add Path support for all AFI/SAFI
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / AdjRibInWriter.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.protocol.bgp.rib.impl;
9
10 import static java.util.Objects.requireNonNull;
11
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;
21 import java.util.Map;
22 import java.util.Map.Entry;
23 import java.util.Set;
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.rev180329.PeerId;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerRole;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.Peer;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.AdjRibIn;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.AdjRibOut;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.EffectiveRibIn;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.SupportedTables;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.Attributes;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
54 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
56 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
57 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
58 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
59 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
60 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
61 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 /**
66  * Writer of Adjacency-RIB-In for a single peer. An instance of this object
67  * is attached to each {@link BGPPeer} and {@link ApplicationPeer}.
68  */
69 @NotThreadSafe
70 final class AdjRibInWriter {
71
72     private static final Logger LOG = LoggerFactory.getLogger(AdjRibInWriter.class);
73
74     @VisibleForTesting
75     static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_FALSE = ImmutableNodes.leafNode(QName.create(Attributes.QNAME,
76             "uptodate"), Boolean.FALSE);
77     @VisibleForTesting
78     static final QName PEER_ID_QNAME = QName.create(Peer.QNAME, "peer-id").intern();
79     private static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_TRUE =
80             ImmutableNodes.leafNode(ATTRIBUTES_UPTODATE_FALSE.getNodeType(), Boolean.TRUE);
81     private static final QName PEER_ROLE_QNAME = QName.create(Peer.QNAME, "peer-role").intern();
82     private static final NodeIdentifier ADJRIBIN = new NodeIdentifier(AdjRibIn.QNAME);
83     private static final NodeIdentifier ADJRIBOUT = new NodeIdentifier(AdjRibOut.QNAME);
84     private static final NodeIdentifier EFFRIBIN = new NodeIdentifier(EffectiveRibIn.QNAME);
85     private static final NodeIdentifier PEER_ID = new NodeIdentifier(PEER_ID_QNAME);
86     private static final NodeIdentifier PEER_ROLE = new NodeIdentifier(PEER_ROLE_QNAME);
87     private static final NodeIdentifier PEER_TABLES = new NodeIdentifier(SupportedTables.QNAME);
88     private static final NodeIdentifier TABLES = new NodeIdentifier(Tables.QNAME);
89     private static final QName SEND_RECEIVE = QName.create(SupportedTables.QNAME, "send-receive").intern();
90
91     // FIXME: is there a utility method to construct this?
92     private static final ContainerNode EMPTY_ADJRIBIN = Builders.containerBuilder()
93             .withNodeIdentifier(ADJRIBIN).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
94     private static final ContainerNode EMPTY_EFFRIBIN = Builders.containerBuilder()
95             .withNodeIdentifier(EFFRIBIN).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
96     private static final ContainerNode EMPTY_ADJRIBOUT = Builders.containerBuilder()
97             .withNodeIdentifier(ADJRIBOUT).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
98
99     private final Map<TablesKey, TableContext> tables;
100     private final YangInstanceIdentifier peerPath;
101     private final YangInstanceIdentifier ribPath;
102     private final DOMTransactionChain chain;
103     private final PeerRole role;
104
105     private AdjRibInWriter(final YangInstanceIdentifier ribPath, final DOMTransactionChain chain, final PeerRole role,
106             final YangInstanceIdentifier peerPath, final Map<TablesKey, TableContext> tables) {
107         this.ribPath = requireNonNull(ribPath);
108         this.chain = requireNonNull(chain);
109         this.tables = requireNonNull(tables);
110         this.role = requireNonNull(role);
111         this.peerPath = peerPath;
112     }
113
114     /**
115      * Create a new writer using a transaction chain.
116      *
117      * @param role                peer's role
118      * @param chain               transaction chain  @return A fresh writer instance
119      */
120     static AdjRibInWriter create(@Nonnull final YangInstanceIdentifier ribId, @Nonnull final PeerRole role,
121             @Nonnull final DOMTransactionChain chain) {
122         return new AdjRibInWriter(ribId, chain, role, null, Collections.emptyMap());
123     }
124
125     /**
126      * Transform this writer to a new writer, which is in charge of specified tables.
127      * Empty tables are created for new entries and old tables are deleted. Once this
128      * method returns, the old instance must not be reasonably used.
129      *
130      * @param newPeerId         new peer BGP identifier
131      * @param registry          RIB extension registry
132      * @param tableTypes        New tables, must not be null
133      * @param addPathTablesType
134      * @return New writer
135      */
136     AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry,
137             final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType) {
138         return transform(newPeerId, registry, tableTypes, addPathTablesType, null);
139     }
140
141     AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry,
142             final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType,
143             @Nullable final RegisterAppPeerListener registerAppPeerListener) {
144         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
145
146         final YangInstanceIdentifier newPeerPath;
147         newPeerPath = createEmptyPeerStructure(newPeerId, tx);
148         final ImmutableMap<TablesKey, TableContext> tb = createNewTableInstances(newPeerPath, registry, tableTypes,
149                 addPathTablesType, tx);
150
151         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
152             @Override
153             public void onSuccess(final Void result) {
154                 if (registerAppPeerListener != null) {
155                     LOG.trace("Application Peer Listener registered");
156                     registerAppPeerListener.register();
157                 }
158             }
159
160             @Override
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",
164                             throwable);
165                 } else {
166                     LOG.error("Failed to create Empty Structure", throwable);
167                 }
168             }
169         }, MoreExecutors.directExecutor());
170         return new AdjRibInWriter(this.ribPath, this.chain, this.role, newPeerPath, tb);
171     }
172
173     /**
174      * Create new table instances, potentially creating their empty entries
175      */
176     private ImmutableMap<TablesKey, TableContext> createNewTableInstances(final YangInstanceIdentifier newPeerPath,
177             final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes,
178             final Map<TablesKey, SendReceive> addPathTablesType, final DOMDataWriteTransaction tx) {
179
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);
185             if (rs == null) {
186                 LOG.warn("No support for table type {}, skipping it", tableKey);
187                 continue;
188             }
189             installAdjRibsOutTables(newPeerPath, rs, instanceIdentifierKey, tableKey, addPathTablesType.get(tableKey), tx);
190             installAdjRibInTables(newPeerPath, tableKey, rs, instanceIdentifierKey, tx, tb);
191         }
192         return tb.build();
193     }
194
195     private static void installAdjRibInTables(final YangInstanceIdentifier newPeerPath, final TablesKey tableKey,
196             final RIBSupportContext rs, final NodeIdentifierWithPredicates instanceIdentifierKey,
197             final DOMDataWriteTransaction tx, final Builder<TablesKey, TableContext> tb) {
198         // We will use table keys very often, make sure they are optimized
199         final InstanceIdentifierBuilder idb = YangInstanceIdentifier.builder(newPeerPath
200                 .node(EMPTY_ADJRIBIN.getIdentifier()).node(TABLES));
201         idb.nodeWithKey(instanceIdentifierKey.getNodeType(), instanceIdentifierKey.getKeyValues());
202
203         final TableContext ctx = new TableContext(rs, idb.build());
204         ctx.createEmptyTableStructure(tx);
205
206         tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(Attributes.QNAME)
207                 .node(ATTRIBUTES_UPTODATE_FALSE.getNodeType()), ATTRIBUTES_UPTODATE_FALSE);
208         LOG.debug("Created table instance {}", ctx.getTableId());
209         tb.put(tableKey, ctx);
210     }
211
212     private void installAdjRibsOutTables(final YangInstanceIdentifier newPeerPath, final RIBSupportContext rs,
213             final NodeIdentifierWithPredicates instanceIdentifierKey, final TablesKey tableKey,
214             final SendReceive sendReceive, final DOMDataWriteTransaction tx) {
215         final NodeIdentifierWithPredicates supTablesKey = RibSupportUtils.toYangKey(SupportedTables.QNAME, tableKey);
216         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> tt =
217                 Builders.mapEntryBuilder().withNodeIdentifier(supTablesKey);
218         for (final Entry<QName, Object> e : supTablesKey.getKeyValues().entrySet()) {
219             tt.withChild(ImmutableNodes.leafNode(e.getKey(), e.getValue()));
220         }
221         if (sendReceive != null) {
222             tt.withChild(ImmutableNodes.leafNode(SEND_RECEIVE, sendReceive.toString().toLowerCase(Locale.ENGLISH)));
223         }
224         tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath.node(PEER_TABLES).node(supTablesKey), tt.build());
225         rs.createEmptyTableStructure(tx, newPeerPath.node(EMPTY_ADJRIBOUT.getIdentifier())
226                 .node(TABLES).node(instanceIdentifierKey));
227     }
228
229     private YangInstanceIdentifier createEmptyPeerStructure(final PeerId newPeerId, final DOMDataWriteTransaction tx) {
230         final NodeIdentifierWithPredicates peerKey = IdentifierUtils.domPeerId(newPeerId);
231         final YangInstanceIdentifier newPeerPath = this.ribPath.node(Peer.QNAME).node(peerKey);
232
233         tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath, peerSkeleton(peerKey, newPeerId.getValue()));
234         LOG.debug("New peer {} structure installed.", newPeerPath);
235         return newPeerPath;
236     }
237
238     @VisibleForTesting
239     MapEntryNode peerSkeleton(final NodeIdentifierWithPredicates peerKey, final String peerId) {
240         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> pb = Builders.mapEntryBuilder();
241         pb.withNodeIdentifier(peerKey);
242         pb.withChild(ImmutableNodes.leafNode(PEER_ID, peerId));
243         pb.withChild(ImmutableNodes.leafNode(PEER_ROLE, PeerRoleUtil.roleForString(this.role)));
244         pb.withChild(ImmutableMapNodeBuilder.create().withNodeIdentifier(PEER_TABLES).build());
245         pb.withChild(EMPTY_ADJRIBIN);
246         pb.withChild(EMPTY_EFFRIBIN);
247         pb.withChild(EMPTY_ADJRIBOUT);
248         return pb.build();
249     }
250
251     synchronized ListenableFuture<Void> removePeer() {
252         if (this.peerPath != null) {
253
254             LOG.info("AdjRibInWriter closed per Peer {} removed", AdjRibInWriter.this.peerPath);
255             final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
256             tx.delete(LogicalDatastoreType.OPERATIONAL, this.peerPath);
257             final ListenableFuture<Void> future = tx.submit();
258             Futures.addCallback(future, new FutureCallback<Void>() {
259                 @Override
260                 public void onSuccess(final Void result) {
261                     LOG.debug("Peer {} removed", AdjRibInWriter.this.peerPath);
262                 }
263
264                 @Override
265                 public void onFailure(final Throwable t) {
266                     LOG.warn("Failed to remove Peer {}", AdjRibInWriter.this.peerPath, t);
267                 }
268             }, MoreExecutors.directExecutor());
269             return future;
270         }
271         return Futures.immediateFuture(null);
272     }
273
274     void markTableUptodate(final TablesKey tableTypes) {
275         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
276         final TableContext ctx = this.tables.get(tableTypes);
277         tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(Attributes.QNAME)
278                 .node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
279         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
280             @Override
281             public void onSuccess(final Void result) {
282                 LOG.trace("Write Attributes uptodate, succeed");
283             }
284
285             @Override
286             public void onFailure(final Throwable throwable) {
287                 LOG.error("Write Attributes uptodate failed", throwable);
288             }
289         }, MoreExecutors.directExecutor());
290     }
291
292     void updateRoutes(final MpReachNlri nlri, final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang
293             .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);
296         if (ctx == null) {
297             LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
298             return;
299         }
300
301         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
302         ctx.writeRoutes(tx, nlri, attributes);
303         LOG.trace("Write routes {}", nlri);
304         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
305             @Override
306             public void onSuccess(final Void result) {
307                 LOG.trace("Write routes {}, succeed", nlri);
308             }
309
310             @Override
311             public void onFailure(final Throwable throwable) {
312                 LOG.error("Write routes failed", throwable);
313             }
314         }, MoreExecutors.directExecutor());
315     }
316
317     void removeRoutes(final MpUnreachNlri nlri) {
318         final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
319         final TableContext ctx = this.tables.get(key);
320         if (ctx == null) {
321             LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
322             return;
323         }
324         LOG.trace("Removing routes {}", nlri);
325         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
326         ctx.removeRoutes(tx, nlri);
327         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
328             @Override
329             public void onSuccess(final Void result) {
330                 LOG.trace("Removing routes {}, succeed", nlri);
331             }
332
333             @Override
334             public void onFailure(final Throwable throwable) {
335                 LOG.error("Removing routes failed", throwable);
336             }
337         }, MoreExecutors.directExecutor());
338     }
339 }