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