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