Replace Preconditions.CheckNotNull per RequireNonNull
[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.rev130919.SendReceive;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlri;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlri;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.SimpleRoutingPolicy;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibIn;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibOut;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.EffectiveRibIn;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.SupportedTables;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.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  * 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     private static final Logger LOG = LoggerFactory.getLogger(AdjRibInWriter.class);
72     @VisibleForTesting
73     static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_FALSE = ImmutableNodes.leafNode(QName.create(Attributes.QNAME, "uptodate"), Boolean.FALSE);
74     private static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_TRUE = ImmutableNodes.leafNode(ATTRIBUTES_UPTODATE_FALSE.getNodeType(), Boolean.TRUE);
75     @VisibleForTesting
76     static final QName PEER_ID_QNAME = QName.create(Peer.QNAME, "peer-id").intern();
77     private static final QName PEER_ROLE_QNAME = QName.create(Peer.QNAME, "peer-role").intern();
78     private static final NodeIdentifier ADJRIBIN = new NodeIdentifier(AdjRibIn.QNAME);
79     private static final NodeIdentifier ADJRIBOUT = new NodeIdentifier(AdjRibOut.QNAME);
80     private static final NodeIdentifier EFFRIBIN = new NodeIdentifier(EffectiveRibIn.QNAME);
81     private static final NodeIdentifier PEER_ID = new NodeIdentifier(PEER_ID_QNAME);
82     private static final NodeIdentifier PEER_ROLE = new NodeIdentifier(PEER_ROLE_QNAME);
83     private static final NodeIdentifier PEER_TABLES = new NodeIdentifier(SupportedTables.QNAME);
84     private static final NodeIdentifier TABLES = new NodeIdentifier(Tables.QNAME);
85     private static final QName SEND_RECEIVE = QName.create(SupportedTables.QNAME, "send-receive").intern();
86     private static final NodeIdentifier SIMPLE_ROUTING_POLICY_NID = new NodeIdentifier(QName.create(Peer.QNAME, "simple-routing-policy").intern());
87
88     // FIXME: is there a utility method to construct this?
89     private static final ContainerNode EMPTY_ADJRIBIN = Builders.containerBuilder().withNodeIdentifier(ADJRIBIN).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
90     private static final ContainerNode EMPTY_EFFRIBIN = Builders.containerBuilder().withNodeIdentifier(EFFRIBIN).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
91     private static final ContainerNode EMPTY_ADJRIBOUT = Builders.containerBuilder().withNodeIdentifier(ADJRIBOUT).addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build()).build();
92
93     private final Map<TablesKey, TableContext> tables;
94     private final YangInstanceIdentifier peerPath;
95     private final YangInstanceIdentifier ribPath;
96     private final DOMTransactionChain chain;
97     private final PeerRole role;
98     private final Optional<SimpleRoutingPolicy> simpleRoutingPolicy;
99
100     private AdjRibInWriter(final YangInstanceIdentifier ribPath, final DOMTransactionChain chain, final PeerRole role,
101         final Optional<SimpleRoutingPolicy> simpleRoutingPolicy, final YangInstanceIdentifier peerPath, final Map<TablesKey, TableContext> tables) {
102         this.ribPath = requireNonNull(ribPath);
103         this.chain = requireNonNull(chain);
104         this.tables = requireNonNull(tables);
105         this.role = requireNonNull(role);
106         this.simpleRoutingPolicy = simpleRoutingPolicy;
107         this.peerPath = peerPath;
108     }
109
110     /**
111      * Create a new writer using a transaction chain.
112      *
113      * @param role peer's role
114      * @param simpleRoutingPolicy simple Routing Policy {@link SimpleRoutingPolicy}
115      *@param chain transaction chain  @return A fresh writer instance
116      */
117     static AdjRibInWriter create(@Nonnull final YangInstanceIdentifier ribId, @Nonnull final PeerRole role,
118         final Optional<SimpleRoutingPolicy> simpleRoutingPolicy, @Nonnull final DOMTransactionChain chain) {
119         return new AdjRibInWriter(ribId, chain, role, simpleRoutingPolicy, null, Collections.emptyMap());
120     }
121
122     /**
123      * Transform this writer to a new writer, which is in charge of specified tables.
124      * Empty tables are created for new entries and old tables are deleted. Once this
125      * method returns, the old instance must not be reasonably used.
126      *
127      * @param newPeerId new peer BGP identifier
128      * @param registry RIB extension registry
129      * @param tableTypes New tables, must not be null
130      * @param addPathTablesType
131      * @return New writer
132      */
133     AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry,
134         final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType) {
135         return transform(newPeerId, registry, tableTypes, addPathTablesType, null);
136     }
137
138     AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes,
139         final Map<TablesKey, SendReceive> addPathTablesType, @Nullable final RegisterAppPeerListener registerAppPeerListener) {
140         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
141
142         final YangInstanceIdentifier newPeerPath;
143         newPeerPath = createEmptyPeerStructure(newPeerId, tx);
144         final ImmutableMap<TablesKey, TableContext> tb = createNewTableInstances(newPeerPath, registry, tableTypes,
145             addPathTablesType, tx);
146
147         Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
148             @Override
149             public void onSuccess(final Void result) {
150                 if(registerAppPeerListener != null) {
151                     LOG.trace("Application Peer Listener registered");
152                     registerAppPeerListener.register();
153                 }
154             }
155
156             @Override
157             public void onFailure(final Throwable throwable) {
158                 if(registerAppPeerListener != null) {
159                     LOG.error("Failed to create Empty Structure, Application Peer Listener won't be registered",
160                         throwable);
161                 } else {
162                     LOG.error("Failed to create Empty Structure", throwable);
163                 }
164             }
165         }, MoreExecutors.directExecutor());
166         return new AdjRibInWriter(this.ribPath, this.chain, this.role, this.simpleRoutingPolicy, newPeerPath, tb);
167     }
168
169     /**
170      * Create new table instances, potentially creating their empty entries
171      * @param newPeerPath
172      * @param registry
173      * @param tableTypes
174      * @param addPathTablesType
175      * @param tx
176      * @return
177      */
178     private ImmutableMap<TablesKey, TableContext> createNewTableInstances(final YangInstanceIdentifier newPeerPath,
179         final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType,
180         final DOMDataWriteTransaction tx) {
181
182         final Builder<TablesKey, TableContext> tb = ImmutableMap.builder();
183         for (final TablesKey tableKey : tableTypes) {
184             final RIBSupportContext rs = registry.getRIBSupportContext(tableKey);
185             // TODO: Use returned value once Instance Identifier builder allows for it.
186             final NodeIdentifierWithPredicates instanceIdentifierKey = RibSupportUtils.toYangTablesKey(tableKey);
187             if (rs == null) {
188                 LOG.warn("No support for table type {}, skipping it", tableKey);
189                 continue;
190             }
191             installAdjRibsOutTables(newPeerPath, rs, instanceIdentifierKey, tableKey, addPathTablesType.get(tableKey), tx);
192             installAdjRibInTables(newPeerPath, tableKey, rs, instanceIdentifierKey, tx, tb);
193         }
194         return tb.build();
195     }
196
197     private static void installAdjRibInTables(final YangInstanceIdentifier newPeerPath, final TablesKey tableKey,
198             final RIBSupportContext rs, final NodeIdentifierWithPredicates instanceIdentifierKey,
199             final DOMDataWriteTransaction tx, final Builder<TablesKey, TableContext> tb) {
200         // We will use table keys very often, make sure they are optimized
201         final InstanceIdentifierBuilder idb = YangInstanceIdentifier.builder(newPeerPath.node(EMPTY_ADJRIBIN.getIdentifier()).node(TABLES));
202         idb.nodeWithKey(instanceIdentifierKey.getNodeType(), instanceIdentifierKey.getKeyValues());
203
204         final TableContext ctx = new TableContext(rs, idb.build());
205         ctx.createEmptyTableStructure(tx);
206
207         tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(Attributes.QNAME).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, final SendReceive sendReceive,
214         final DOMDataWriteTransaction tx) {
215         if (!isAnnounceNone(this.simpleRoutingPolicy)) {
216             final NodeIdentifierWithPredicates supTablesKey = RibSupportUtils.toYangKey(SupportedTables.QNAME, tableKey);
217             final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> tt = 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()));
223             }
224             tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath.node(PEER_TABLES).node(supTablesKey), tt.build());
225             rs.createEmptyTableStructure(tx, newPeerPath.node(EMPTY_ADJRIBOUT.getIdentifier()).node(TABLES).node(instanceIdentifierKey));
226         }
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         if (this.simpleRoutingPolicy.isPresent() && this.role != PeerRole.Internal) {
245             pb.withChild(ImmutableNodes.leafNode(SIMPLE_ROUTING_POLICY_NID, simpleRoutingPolicyString(this.simpleRoutingPolicy.get())));
246         }
247         pb.withChild(ImmutableMapNodeBuilder.create().withNodeIdentifier(PEER_TABLES).build());
248         pb.withChild(EMPTY_ADJRIBIN);
249         if(!isLearnNone(this.simpleRoutingPolicy)) {
250             pb.withChild(EMPTY_EFFRIBIN);
251         }
252         if (!isAnnounceNone(this.simpleRoutingPolicy)) {
253             pb.withChild(EMPTY_ADJRIBOUT);
254         }
255         return pb.build();
256     }
257
258     ListenableFuture<Void> removePeer() {
259         if(this.peerPath != null) {
260             final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
261             tx.delete(LogicalDatastoreType.OPERATIONAL, this.peerPath);
262             final ListenableFuture<Void> future = tx.submit();
263             Futures.addCallback(future, new FutureCallback<Void>() {
264                 @Override
265                 public void onSuccess(final Void result) {
266                     LOG.debug("Peer {} removed", AdjRibInWriter.this.peerPath);
267                 }
268
269                 @Override
270                 public void onFailure(final Throwable t) {
271                     LOG.warn("Failed to remove Peer {}", AdjRibInWriter.this.peerPath, t);
272                 }
273             }, MoreExecutors.directExecutor());
274             return future;
275         }
276         return Futures.immediateFuture(null);
277     }
278
279     void markTableUptodate(final TablesKey tableTypes) {
280         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
281         final TableContext ctx = this.tables.get(tableTypes);
282         tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
283         tx.submit();
284     }
285
286     void updateRoutes(final MpReachNlri nlri, final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.Attributes attributes) {
287         final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
288         final TableContext ctx = this.tables.get(key);
289         if (ctx == null) {
290             LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
291             return;
292         }
293
294         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
295         ctx.writeRoutes(tx, nlri, attributes);
296         LOG.trace("Write routes {}", nlri);
297         tx.submit();
298     }
299
300     void removeRoutes(final MpUnreachNlri nlri) {
301         final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
302         final TableContext ctx = this.tables.get(key);
303         if (ctx == null) {
304             LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
305             return;
306         }
307         LOG.trace("Removing routes {}", nlri);
308         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
309         ctx.removeRoutes(tx, nlri);
310         tx.submit();
311     }
312
313     static boolean isAnnounceNone(final java.util.Optional<SimpleRoutingPolicy> peerStatus) {
314         return peerStatus.isPresent() && peerStatus.get() == SimpleRoutingPolicy.AnnounceNone;
315     }
316
317     static boolean isLearnNone(final java.util.Optional<SimpleRoutingPolicy> peerStatus) {
318         return peerStatus.isPresent() && peerStatus.get() == SimpleRoutingPolicy.LearnNone;
319     }
320
321     private static String simpleRoutingPolicyString(final SimpleRoutingPolicy simpleRoutingPolicy) {
322         switch (simpleRoutingPolicy) {
323         case AnnounceNone:
324             return "announce-none";
325         case LearnNone:
326             return "learn-none";
327         default:
328             throw new IllegalArgumentException("Unhandled Simple Routing Policy " + simpleRoutingPolicy);
329         }
330     }
331 }