64c9075b78f16933d611fee59303173ffc72ed9a
[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.Map;
21 import java.util.Map.Entry;
22 import java.util.Optional;
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.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;
65
66 /**
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}.
69  */
70 @NotThreadSafe
71 final class AdjRibInWriter {
72
73     private static final Logger LOG = LoggerFactory.getLogger(AdjRibInWriter.class);
74
75     @VisibleForTesting
76     static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_FALSE = ImmutableNodes.leafNode(QName.create(Attributes.QNAME, "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 = 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());
90
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();
95
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;
102
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;
112     }
113
114     /**
115      * Create a new writer using a transaction chain.
116      *
117      * @param role                peer's role
118      * @param simpleRoutingPolicy simple Routing Policy {@link SimpleRoutingPolicy}
119      * @param chain               transaction chain  @return A fresh writer instance
120      */
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());
124     }
125
126     /**
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.
130      *
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
135      * @return New writer
136      */
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);
140     }
141
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();
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, this.simpleRoutingPolicy, newPeerPath, tb);
171     }
172
173     /**
174      * Create new table instances, potentially creating their empty entries
175      *
176      * @param newPeerPath
177      * @param registry
178      * @param tableTypes
179      * @param addPathTablesType
180      * @param tx
181      * @return
182      */
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) {
186
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);
192             if (rs == null) {
193                 LOG.warn("No support for table type {}, skipping it", tableKey);
194                 continue;
195             }
196             installAdjRibsOutTables(newPeerPath, rs, instanceIdentifierKey, tableKey, addPathTablesType.get(tableKey), tx);
197             installAdjRibInTables(newPeerPath, tableKey, rs, instanceIdentifierKey, tx, tb);
198         }
199         return tb.build();
200     }
201
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());
208
209         final TableContext ctx = new TableContext(rs, idb.build());
210         ctx.createEmptyTableStructure(tx);
211
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);
215     }
216
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()));
225             }
226             if (sendReceive != null) {
227                 tt.withChild(ImmutableNodes.leafNode(SEND_RECEIVE, sendReceive.toString().toLowerCase()));
228             }
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));
231         }
232     }
233
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);
237
238         tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath, peerSkeleton(peerKey, newPeerId.getValue()));
239         LOG.debug("New peer {} structure installed.", newPeerPath);
240         return newPeerPath;
241     }
242
243     @VisibleForTesting
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())));
251         }
252         pb.withChild(ImmutableMapNodeBuilder.create().withNodeIdentifier(PEER_TABLES).build());
253         pb.withChild(EMPTY_ADJRIBIN);
254         if (!isLearnNone(this.simpleRoutingPolicy)) {
255             pb.withChild(EMPTY_EFFRIBIN);
256         }
257         if (!isAnnounceNone(this.simpleRoutingPolicy)) {
258             pb.withChild(EMPTY_ADJRIBOUT);
259         }
260         return pb.build();
261     }
262
263     synchronized ListenableFuture<Void> removePeer() {
264         if (this.peerPath != null) {
265
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>() {
271                 @Override
272                 public void onSuccess(final Void result) {
273                     LOG.debug("Peer {} removed", AdjRibInWriter.this.peerPath);
274                 }
275
276                 @Override
277                 public void onFailure(final Throwable t) {
278                     LOG.warn("Failed to remove Peer {}", AdjRibInWriter.this.peerPath, t);
279                 }
280             }, MoreExecutors.directExecutor());
281             return future;
282         }
283         return Futures.immediateFuture(null);
284     }
285
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);
290         tx.submit();
291     }
292
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);
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         tx.submit();
305     }
306
307     void removeRoutes(final MpUnreachNlri nlri) {
308         final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
309         final TableContext ctx = this.tables.get(key);
310         if (ctx == null) {
311             LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
312             return;
313         }
314         LOG.trace("Removing routes {}", nlri);
315         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
316         ctx.removeRoutes(tx, nlri);
317         tx.submit();
318     }
319
320     static boolean isAnnounceNone(final java.util.Optional<SimpleRoutingPolicy> peerStatus) {
321         return peerStatus.isPresent() && peerStatus.get() == SimpleRoutingPolicy.AnnounceNone;
322     }
323
324     static boolean isLearnNone(final java.util.Optional<SimpleRoutingPolicy> peerStatus) {
325         return peerStatus.isPresent() && peerStatus.get() == SimpleRoutingPolicy.LearnNone;
326     }
327
328     private static String simpleRoutingPolicyString(final SimpleRoutingPolicy simpleRoutingPolicy) {
329         switch (simpleRoutingPolicy) {
330             case AnnounceNone:
331                 return "announce-none";
332             case LearnNone:
333                 return "learn-none";
334             default:
335                 throw new IllegalArgumentException("Unhandled Simple Routing Policy " + simpleRoutingPolicy);
336         }
337     }
338 }