85ba578f354df65a3ac5e801696ee52f6f05498a
[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 java.util.Collections;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import java.util.Optional;
19 import java.util.Set;
20 import java.util.stream.Collectors;
21 import javax.annotation.Nonnull;
22 import javax.annotation.concurrent.NotThreadSafe;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
25 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
26 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
27 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
28 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
29 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
30 import org.opendaylight.protocol.bgp.rib.spi.PeerRoleUtil;
31 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.SendReceive;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.add.path.capability.AddressFamilies;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpReachNlri;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.attributes.MpUnreachNlri;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.SimpleRoutingPolicy;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibIn;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibOut;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.EffectiveRibIn;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.SupportedTables;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Attributes;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
52 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
55 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
56 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
57 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
58 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
59 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 /**
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}.
66  */
67 @NotThreadSafe
68 final class AdjRibInWriter {
69     private static final Logger LOG = LoggerFactory.getLogger(AdjRibInWriter.class);
70     @VisibleForTesting
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);
73     @VisibleForTesting
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     static final NodeIdentifier SIMPLE_ROUTING_POLICY_NID = new NodeIdentifier(QName.create(Peer.QNAME, "simple-routing-policy").intern());
85
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();
90
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;
97
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;
106     }
107
108     /**
109      * Create a new writer using a transaction chain.
110      *
111      * @param role peer's role
112      * @param simpleRoutingPolicy simple Routing Policy {@link SimpleRoutingPolicy}
113      *@param chain transaction chain  @return A fresh writer instance
114      */
115     static AdjRibInWriter create(@Nonnull final YangInstanceIdentifier ribId, @Nonnull final PeerRole role, final Optional<SimpleRoutingPolicy> simpleRoutingPolicy,
116         @Nonnull final DOMTransactionChain chain) {
117         return new AdjRibInWriter(ribId, chain, role, simpleRoutingPolicy, null, Collections.emptyMap());
118     }
119
120     /**
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.
124      *
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
129      * @return New writer
130      */
131     AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes,
132         final List<AddressFamilies> addPathTablesType) {
133         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
134
135         final YangInstanceIdentifier newPeerPath;
136         newPeerPath = createEmptyPeerStructure(newPeerId, tx);
137         final ImmutableMap<TablesKey, TableContext> tb = createNewTableInstances(newPeerPath, registry, tableTypes, addPathTablesType, tx);
138         tx.submit();
139
140         return new AdjRibInWriter(this.ribPath, this.chain, this.role, this.simpleRoutingPolicy, newPeerPath, tb);
141     }
142
143     /**
144      * Create new table instances, potentially creating their empty entries
145      * @param newPeerPath
146      * @param registry
147      * @param tableTypes
148      * @param addPathTablesType
149      * @param tx
150      * @return
151      */
152     private ImmutableMap<TablesKey, TableContext> createNewTableInstances(final YangInstanceIdentifier newPeerPath,
153         final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes, final List<AddressFamilies> addPathTablesType,
154         final DOMDataWriteTransaction tx) {
155
156         final Map<TablesKey, SendReceive> addPathTableMaps = mapTableTypesFamilies(addPathTablesType);
157         final Builder<TablesKey, TableContext> tb = ImmutableMap.builder();
158         for (final TablesKey tableKey : tableTypes) {
159             final RIBSupportContext rs = registry.getRIBSupportContext(tableKey);
160             // TODO: Use returned value once Instance Identifier builder allows for it.
161             final NodeIdentifierWithPredicates instanceIdentifierKey = RibSupportUtils.toYangTablesKey(tableKey);
162             if (rs == null) {
163                 LOG.warn("No support for table type {}, skipping it", tableKey);
164                 continue;
165             }
166             installAdjRibsOutTables(newPeerPath, rs, instanceIdentifierKey, tableKey, addPathTableMaps.get(tableKey), tx);
167             installAdjRibInTables(newPeerPath, tableKey, rs, instanceIdentifierKey, tx, tb);
168         }
169         return tb.build();
170     }
171
172     private Map<TablesKey, SendReceive> mapTableTypesFamilies(final List<AddressFamilies> addPathTablesType) {
173         return Collections.unmodifiableMap(addPathTablesType.stream().collect(Collectors.toMap(af -> new TablesKey(af.getAfi(), af.getSafi()),
174             af -> af.getSendReceive())));
175     }
176
177     private void installAdjRibInTables(final YangInstanceIdentifier newPeerPath, final TablesKey tableKey, final RIBSupportContext rs,
178         final NodeIdentifierWithPredicates instanceIdentifierKey, final DOMDataWriteTransaction tx, final Builder<TablesKey, TableContext> tb) {
179         // We will use table keys very often, make sure they are optimized
180         final InstanceIdentifierBuilder idb = YangInstanceIdentifier.builder(newPeerPath.node(EMPTY_ADJRIBIN.getIdentifier()).node(TABLES));
181         idb.nodeWithKey(instanceIdentifierKey.getNodeType(), instanceIdentifierKey.getKeyValues());
182
183         final TableContext ctx = new TableContext(rs, idb.build());
184         ctx.createEmptyTableStructure(tx);
185
186         tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_FALSE.getNodeType()), ATTRIBUTES_UPTODATE_FALSE);
187         LOG.debug("Created table instance {}", ctx.getTableId());
188         tb.put(tableKey, ctx);
189     }
190
191     private void installAdjRibsOutTables(final YangInstanceIdentifier newPeerPath, final RIBSupportContext rs,
192         final NodeIdentifierWithPredicates instanceIdentifierKey, final TablesKey tableKey, final SendReceive sendReceive,
193         final DOMDataWriteTransaction tx) {
194         if (!isAnnounceNone(this.simpleRoutingPolicy)) {
195             final NodeIdentifierWithPredicates supTablesKey = RibSupportUtils.toYangKey(SupportedTables.QNAME, tableKey);
196             final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> tt = Builders.mapEntryBuilder().withNodeIdentifier(supTablesKey);
197             for (final Entry<QName, Object> e : supTablesKey.getKeyValues().entrySet()) {
198                 tt.withChild(ImmutableNodes.leafNode(e.getKey(), e.getValue()));
199             }
200             if(sendReceive != null) {
201                 tt.withChild(ImmutableNodes.leafNode(SEND_RECEIVE, sendReceive.toString().toLowerCase()));
202             }
203             tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath.node(PEER_TABLES).node(supTablesKey), tt.build());
204             rs.createEmptyTableStructure(tx, newPeerPath.node(EMPTY_ADJRIBOUT.getIdentifier()).node(TABLES).node(instanceIdentifierKey));
205         }
206     }
207
208     private YangInstanceIdentifier createEmptyPeerStructure(final PeerId newPeerId, final DOMDataWriteTransaction tx) {
209         final NodeIdentifierWithPredicates peerKey = IdentifierUtils.domPeerId(newPeerId);
210         final YangInstanceIdentifier newPeerPath = this.ribPath.node(Peer.QNAME).node(peerKey);
211
212         tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath, peerSkeleton(peerKey, newPeerId.getValue()));
213         LOG.debug("New peer {} structure installed.", newPeerPath);
214         return newPeerPath;
215     }
216
217     @VisibleForTesting
218     MapEntryNode peerSkeleton(final NodeIdentifierWithPredicates peerKey, final String peerId) {
219         final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> pb = Builders.mapEntryBuilder();
220         pb.withNodeIdentifier(peerKey);
221         pb.withChild(ImmutableNodes.leafNode(PEER_ID, peerId));
222         pb.withChild(ImmutableNodes.leafNode(PEER_ROLE, PeerRoleUtil.roleForString(this.role)));
223         if (this.simpleRoutingPolicy.isPresent() && this.role != PeerRole.Internal) {
224             pb.withChild(ImmutableNodes.leafNode(SIMPLE_ROUTING_POLICY_NID, simpleRoutingPolicyString(this.simpleRoutingPolicy.get())));
225         }
226         pb.withChild(ImmutableMapNodeBuilder.create().withNodeIdentifier(PEER_TABLES).build());
227         pb.withChild(EMPTY_ADJRIBIN);
228         if(!isLearnNone(this.simpleRoutingPolicy)) {
229             pb.withChild(EMPTY_EFFRIBIN);
230         }
231         if (!isAnnounceNone(this.simpleRoutingPolicy)) {
232             pb.withChild(EMPTY_ADJRIBOUT);
233         }
234         return pb.build();
235     }
236
237     void removePeer() {
238         if(this.peerPath != null) {
239             final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
240             tx.delete(LogicalDatastoreType.OPERATIONAL, this.peerPath);
241
242             try {
243                 tx.submit().checkedGet();
244             } catch (final TransactionCommitFailedException e) {
245                 LOG.debug("Failed to remove Peer {}", this.peerPath, e);
246             }
247         }
248     }
249
250     void markTableUptodate(final TablesKey tableTypes) {
251         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
252         final TableContext ctx = this.tables.get(tableTypes);
253         tx.merge(LogicalDatastoreType.OPERATIONAL, ctx.getTableId().node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
254         tx.submit();
255     }
256
257     void updateRoutes(final MpReachNlri nlri, final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.path.attributes.Attributes attributes) {
258         final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
259         final TableContext ctx = this.tables.get(key);
260         if (ctx == null) {
261             LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
262             return;
263         }
264
265         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
266         ctx.writeRoutes(tx, nlri, attributes);
267         LOG.trace("Write routes {}", nlri);
268         tx.submit();
269     }
270
271     void removeRoutes(final MpUnreachNlri nlri) {
272         final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
273         final TableContext ctx = this.tables.get(key);
274         if (ctx == null) {
275             LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
276             return;
277         }
278         LOG.trace("Removing routes {}", nlri);
279         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
280         ctx.removeRoutes(tx, nlri);
281         tx.submit();
282     }
283
284     static boolean isAnnounceNone(final java.util.Optional<SimpleRoutingPolicy> peerStatus) {
285         return peerStatus.isPresent() && peerStatus.get() == SimpleRoutingPolicy.AnnounceNone;
286     }
287
288     static boolean isLearnNone(final java.util.Optional<SimpleRoutingPolicy> peerStatus) {
289         return peerStatus.isPresent() && peerStatus.get() == SimpleRoutingPolicy.LearnNone;
290     }
291
292     private static String simpleRoutingPolicyString(final SimpleRoutingPolicy simpleRoutingPolicy) {
293         switch (simpleRoutingPolicy) {
294         case AnnounceNone:
295             return "announce-none";
296         case LearnNone:
297             return "learn-none";
298         default:
299             throw new IllegalArgumentException("Unhandled Simple Routing Policy " + simpleRoutingPolicy);
300         }
301     }
302 }