Fixup Augmentable and Identifiable methods changing
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / EffectiveRibInWriter.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.collect.ImmutableMap;
13 import com.google.common.collect.ImmutableSet;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.MoreExecutors;
16 import java.util.Collection;
17 import java.util.Map;
18 import java.util.Optional;
19 import java.util.Set;
20 import java.util.concurrent.atomic.LongAdder;
21 import javax.annotation.Nonnull;
22 import javax.annotation.concurrent.NotThreadSafe;
23 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
24 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
25 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
26 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
27 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
28 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
29 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
30 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
31 import org.opendaylight.mdsal.common.api.CommitInfo;
32 import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
33 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
34 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
35 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesInstalledCounters;
36 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesReceivedCounters;
37 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
38 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRibRoutingPolicy;
39 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryImportParameters;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.Attributes;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.Route;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.Peer;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.PeerKey;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.AdjRibIn;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.EffectiveRibIn;
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.TablesBuilder;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.Routes;
50 import org.opendaylight.yangtools.concepts.ListenerRegistration;
51 import org.opendaylight.yangtools.yang.binding.ChildOf;
52 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
53 import org.opendaylight.yangtools.yang.binding.DataObject;
54 import org.opendaylight.yangtools.yang.binding.Identifiable;
55 import org.opendaylight.yangtools.yang.binding.Identifier;
56 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
57 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 /**
63  * Implementation of the BGP import policy. Listens on peer's Adj-RIB-In, inspects all inbound
64  * routes in the context of the advertising peer's role and applies the inbound policy.
65  * <p>
66  * Inbound policy is applied as follows:
67  * <p>
68  * 1) if the peer is an eBGP peer, perform attribute replacement and filtering
69  * 2) check if a route is admissible based on attributes attached to it, as well as the
70  * advertising peer's role
71  * 3) output admitting routes with edited attributes into /bgp-rib/rib/peer/effective-rib-in/tables/routes
72  */
73 @NotThreadSafe
74 final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesInstalledCounters,
75         AutoCloseable, ClusteredDataTreeChangeListener<Tables> {
76
77     private static final Logger LOG = LoggerFactory.getLogger(EffectiveRibInWriter.class);
78     static final NodeIdentifier TABLE_ROUTES = new NodeIdentifier(Routes.QNAME);
79
80     private final RIBSupportContextRegistry registry;
81     private final KeyedInstanceIdentifier<Peer, PeerKey> peerIId;
82     private final InstanceIdentifier<EffectiveRibIn> effRibTables;
83     private final DataBroker databroker;
84     private ListenerRegistration<?> reg;
85     private BindingTransactionChain chain;
86     private final Map<TablesKey, LongAdder> prefixesReceived;
87     private final Map<TablesKey, LongAdder> prefixesInstalled;
88     private final BGPRibRoutingPolicy ribPolicies;
89     private final BGPRouteEntryImportParameters peerImportParameters;
90     private final BGPTableTypeRegistryConsumer tableTypeRegistry;
91
92     EffectiveRibInWriter(
93             final BGPRouteEntryImportParameters peer,
94             final RIB rib,
95             final BindingTransactionChain chain,
96             final KeyedInstanceIdentifier<Peer, PeerKey> peerIId,
97             final Set<TablesKey> tables,
98             final BGPTableTypeRegistryConsumer tableTypeRegistry
99     ) {
100         this.registry = requireNonNull(rib.getRibSupportContext());
101         this.chain = requireNonNull(chain);
102         this.peerIId = requireNonNull(peerIId);
103         this.effRibTables = this.peerIId.child(EffectiveRibIn.class);
104         this.prefixesInstalled = buildPrefixesTables(tables);
105         this.prefixesReceived = buildPrefixesTables(tables);
106         this.ribPolicies = requireNonNull(rib.getRibPolicies());
107         this.databroker = requireNonNull(rib.getDataBroker());
108         this.tableTypeRegistry = requireNonNull(tableTypeRegistry);
109         this.peerImportParameters = peer;
110     }
111
112     public void init() {
113         final DataTreeIdentifier<Tables> treeId = new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL,
114                 this.peerIId.child(AdjRibIn.class).child(Tables.class));
115         LOG.debug("Registered Effective RIB on {}", this.peerIId);
116         this.reg = requireNonNull(this.databroker).registerDataTreeChangeListener(treeId, this);
117     }
118
119     private static Map<TablesKey, LongAdder> buildPrefixesTables(final Set<TablesKey> tables) {
120         final ImmutableMap.Builder<TablesKey, LongAdder> b = ImmutableMap.builder();
121         tables.forEach(table -> b.put(table, new LongAdder()));
122         return b.build();
123     }
124
125     @Override
126     @SuppressWarnings("unchecked")
127     public synchronized void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<Tables>> changes) {
128         if (this.chain == null) {
129             LOG.trace("Chain closed. Ignoring Changes : {}", changes);
130             return;
131         }
132         LOG.trace("Data changed called to effective RIB. Change : {}", changes);
133         WriteTransaction tx = null;
134         for (final DataTreeModification<Tables> tc : changes) {
135             final DataObjectModification<Tables> table = tc.getRootNode();
136             if (tx == null) {
137                 tx = this.chain.newWriteOnlyTransaction();
138             }
139             final DataObjectModification.ModificationType modificationType = table.getModificationType();
140             switch (modificationType) {
141                 case DELETE:
142                     final Tables removeTable = table.getDataBefore();
143                     final TablesKey tableKey = removeTable.key();
144                     final KeyedInstanceIdentifier<Tables, TablesKey> effectiveTablePath
145                             = this.effRibTables.child(Tables.class, tableKey);
146                     LOG.debug("Delete Effective Table {} modification type {}, "
147                             , effectiveTablePath, modificationType);
148                     tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath);
149                     CountersUtil.decrement(this.prefixesInstalled.get(tableKey), tableKey);
150                     break;
151                 case SUBTREE_MODIFIED:
152                     final Tables before = table.getDataBefore();
153                     final Tables after = table.getDataAfter();
154                     final TablesKey tk = after.key();
155                     LOG.debug("Process table {} type {}, dataAfter {}, dataBefore {}",
156                             tk, modificationType, after, before);
157
158                     final KeyedInstanceIdentifier<Tables, TablesKey> tablePath
159                             = this.effRibTables.child(Tables.class, tk);
160                     final RIBSupport ribSupport = this.registry.getRIBSupport(tk);
161                     if (ribSupport == null) {
162                         break;
163                     }
164                     tx.put(LogicalDatastoreType.OPERATIONAL,
165                             tablePath.child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp
166                                     .rib.rev180329.rib.tables.Attributes.class), after.getAttributes());
167
168                     final DataObjectModification routesChangesContainer =
169                             table.getModifiedChildContainer(ribSupport.routesContainerClass());
170
171                     if (routesChangesContainer == null) {
172                         break;
173                     }
174                     updateRoutes(tx, tk, ribSupport, tablePath, routesChangesContainer.getModifiedChildren());
175                     break;
176                 case WRITE:
177                     writeTable(tx, table);
178                     break;
179                 default:
180                     LOG.warn("Ignoring unhandled root {}", table);
181                     break;
182             }
183         }
184         if (tx != null) {
185             tx.commit().addCallback(new FutureCallback<CommitInfo>() {
186                 @Override
187                 public void onSuccess(final CommitInfo result) {
188                     LOG.trace("Successful commit");
189                 }
190
191                 @Override
192                 public void onFailure(final Throwable trw) {
193                     LOG.error("Failed commit", trw);
194                 }
195             }, MoreExecutors.directExecutor());
196         }
197     }
198
199     @SuppressWarnings("unchecked")
200     private <C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
201         R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>> void updateRoutes(
202             final WriteTransaction tx,
203             final TablesKey tableKey, final RIBSupport<C, S, R, I> ribSupport,
204             final KeyedInstanceIdentifier<Tables, TablesKey> tablePath,
205             final Collection<DataObjectModification<? extends DataObject>> routeChanges) {
206         for (final DataObjectModification<? extends DataObject> routeChanged : routeChanges) {
207             final I routeKey
208                     = ((InstanceIdentifier.IdentifiableItem<R, I>) routeChanged.getIdentifier()).getKey();
209             switch (routeChanged.getModificationType()) {
210                 case SUBTREE_MODIFIED:
211                 case WRITE:
212                     writeRoutes(tx, tableKey, ribSupport, tablePath, routeKey, (R) routeChanged.getDataAfter());
213                     break;
214                 case DELETE:
215                     final InstanceIdentifier<R> routeIID = ribSupport.createRouteIdentifier(tablePath, routeKey);
216                     tx.delete(LogicalDatastoreType.OPERATIONAL, routeIID);
217                     break;
218             }
219         }
220     }
221
222     private <C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
223         R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>> void writeRoutes(
224                 final WriteTransaction tx, final TablesKey tk, final RIBSupport<C, S, R, I> ribSupport,
225             final KeyedInstanceIdentifier<Tables, TablesKey> tablePath, final I routeKey,
226             final R route) {
227         final InstanceIdentifier<R> routeIID = ribSupport.createRouteIdentifier(tablePath, routeKey);
228         CountersUtil.increment(this.prefixesReceived.get(tk), tk);
229         final Optional<Attributes> effAtt = this.ribPolicies
230                 .applyImportPolicies(this.peerImportParameters, route.getAttributes(),
231                         tableTypeRegistry.getAfiSafiType(ribSupport.getTablesKey()).get());
232         if (effAtt.isPresent()) {
233             CountersUtil.increment(this.prefixesInstalled.get(tk), tk);
234             tx.put(LogicalDatastoreType.OPERATIONAL, routeIID, route);
235             tx.put(LogicalDatastoreType.OPERATIONAL, routeIID.child(Attributes.class), effAtt.get());
236         } else {
237             tx.delete(LogicalDatastoreType.OPERATIONAL, routeIID);
238         }
239     }
240
241     @SuppressWarnings("unchecked")
242     private void writeTable(final WriteTransaction tx, final DataObjectModification<Tables> table) {
243         final Tables newTable = table.getDataAfter();
244         if (newTable == null) {
245             return;
246         }
247         final TablesKey tableKey = newTable.key();
248         final KeyedInstanceIdentifier<Tables, TablesKey> tablePath
249                 = this.effRibTables.child(Tables.class, tableKey);
250
251         // Create an empty table
252         LOG.trace("Create Empty table", tablePath);
253         if (table.getDataBefore() == null) {
254             tx.put(LogicalDatastoreType.OPERATIONAL, tablePath, new TablesBuilder()
255                     .setAfi(tableKey.getAfi()).setSafi(tableKey.getSafi())
256                     .setRoutes(this.registry.getRIBSupport(tableKey).emptyRoutesCase())
257                     .setAttributes(newTable.getAttributes()).build());
258         }
259
260         final RIBSupport ribSupport = this.registry.getRIBSupport(tableKey);
261         final Routes routes = newTable.getRoutes();
262         if (ribSupport == null || routes == null) {
263             return;
264         }
265
266         final DataObjectModification routesChangesContainer =
267                 table.getModifiedChildContainer(ribSupport.routesContainerClass());
268
269         if (routesChangesContainer == null) {
270             return;
271         }
272         updateRoutes(tx, tableKey, ribSupport, tablePath, routesChangesContainer.getModifiedChildren());
273     }
274
275     @Override
276     public synchronized void close() {
277         if (this.reg != null) {
278             this.reg.close();
279             this.reg = null;
280         }
281         if (this.chain != null) {
282             this.chain.close();
283             this.chain = null;
284         }
285         this.prefixesReceived.values().forEach(LongAdder::reset);
286         this.prefixesInstalled.values().forEach(LongAdder::reset);
287     }
288
289     @Override
290     public long getPrefixedReceivedCount(final TablesKey tablesKey) {
291         final LongAdder counter = this.prefixesReceived.get(tablesKey);
292         if (counter == null) {
293             return 0;
294         }
295         return counter.longValue();
296     }
297
298     @Override
299     public Set<TablesKey> getTableKeys() {
300         return ImmutableSet.copyOf(this.prefixesReceived.keySet());
301     }
302
303     @Override
304     public boolean isSupported(final TablesKey tablesKey) {
305         return this.prefixesReceived.containsKey(tablesKey);
306     }
307
308     @Override
309     public long getPrefixedInstalledCount(final TablesKey tablesKey) {
310         final LongAdder counter = this.prefixesInstalled.get(tablesKey);
311         if (counter == null) {
312             return 0;
313         }
314         return counter.longValue();
315     }
316
317     @Override
318     public long getTotalPrefixesInstalled() {
319         return this.prefixesInstalled.values().stream().mapToLong(LongAdder::longValue).sum();
320     }
321 }