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