2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.bgp.rib.impl;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.MoreExecutors;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.HashMap;
17 import java.util.List;
19 import java.util.Map.Entry;
21 import java.util.concurrent.atomic.LongAdder;
22 import org.checkerframework.checker.lock.qual.GuardedBy;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
25 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
26 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
27 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
28 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
29 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
30 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
31 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
32 import org.opendaylight.mdsal.common.api.CommitInfo;
33 import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode;
34 import org.opendaylight.protocol.bgp.mode.api.RouteEntry;
35 import org.opendaylight.protocol.bgp.rib.impl.spi.RibOutRefresh;
36 import org.opendaylight.protocol.bgp.rib.impl.state.rib.TotalPathsCounter;
37 import org.opendaylight.protocol.bgp.rib.impl.state.rib.TotalPrefixesCounter;
38 import org.opendaylight.protocol.bgp.rib.spi.BGPPeerTracker;
39 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
40 import org.opendaylight.protocol.bgp.rib.spi.RouterId;
41 import org.opendaylight.protocol.bgp.rib.spi.entry.ActualBestPathRoutes;
42 import org.opendaylight.protocol.bgp.rib.spi.entry.AdvertizedRoute;
43 import org.opendaylight.protocol.bgp.rib.spi.entry.StaleBestPathRoute;
44 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRibRoutingPolicy;
45 import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.AfiSafiType;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.PathId;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerId;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.Route;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.Rib;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.RibKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.LocRib;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.Peer;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.PeerKey;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.EffectiveRibIn;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.Attributes;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.AttributesBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.Routes;
61 import org.opendaylight.yangtools.concepts.ListenerRegistration;
62 import org.opendaylight.yangtools.yang.binding.ChildOf;
63 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
64 import org.opendaylight.yangtools.yang.binding.DataObject;
65 import org.opendaylight.yangtools.yang.binding.Identifiable;
66 import org.opendaylight.yangtools.yang.binding.Identifier;
67 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
68 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
72 // This class is NOT thread-safe
73 final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
74 R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>>
75 implements AutoCloseable, RibOutRefresh, TotalPrefixesCounter, TotalPathsCounter,
76 ClusteredDataTreeChangeListener<Tables> {
78 private static final Logger LOG = LoggerFactory.getLogger(LocRibWriter.class);
80 private final Map<String, RouteEntry<C, S, R, I>> routeEntries = new HashMap<>();
81 private final long ourAs;
82 private final RIBSupport<C, S, R, I> ribSupport;
83 private final DataBroker dataBroker;
84 private final PathSelectionMode pathSelectionMode;
85 private final LongAdder totalPathsCounter = new LongAdder();
86 private final LongAdder totalPrefixesCounter = new LongAdder();
87 private final RouteEntryDependenciesContainerImpl entryDep;
88 private final BGPPeerTracker peerTracker;
89 private final KeyedInstanceIdentifier<Rib, RibKey> ribIId;
90 private final KeyedInstanceIdentifier<Tables, TablesKey> locRibTableIID;
92 private BindingTransactionChain chain;
94 private ListenerRegistration<?> reg;
96 private LocRibWriter(final RIBSupport<C, S, R, I> ribSupport,
97 final BindingTransactionChain chain,
98 final KeyedInstanceIdentifier<Rib, RibKey> ribIId,
100 final DataBroker dataBroker,
101 final BGPRibRoutingPolicy ribPolicies,
102 final BGPPeerTracker peerTracker,
103 final Class<? extends AfiSafiType> afiSafiType,
104 final PathSelectionMode pathSelectionMode) {
105 this.chain = requireNonNull(chain);
106 this.ribIId = requireNonNull(ribIId);
107 this.ribSupport = requireNonNull(ribSupport);
108 this.locRibTableIID = ribIId.child(LocRib.class).child(Tables.class, ribSupport.getTablesKey());
110 this.dataBroker = requireNonNull(dataBroker);
111 this.peerTracker = peerTracker;
112 this.pathSelectionMode = pathSelectionMode;
114 this.entryDep = new RouteEntryDependenciesContainerImpl(this.ribSupport, this.peerTracker, ribPolicies,
115 afiSafiType, this.locRibTableIID);
119 public static <C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
120 R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>>
121 LocRibWriter<C, S, R, I> create(
122 final @NonNull RIBSupport<C, S, R, I> ribSupport,
123 final @NonNull Class<? extends AfiSafiType> afiSafiType,
124 final @NonNull BindingTransactionChain chain,
125 final @NonNull KeyedInstanceIdentifier<Rib, RibKey> ribIId,
126 final @NonNull AsNumber ourAs,
127 final @NonNull DataBroker dataBroker,
128 final BGPRibRoutingPolicy ribPolicies,
129 final @NonNull BGPPeerTracker peerTracker,
130 final @NonNull PathSelectionMode pathSelectionStrategy) {
131 return new LocRibWriter<>(ribSupport, chain, ribIId, ourAs.getValue(), dataBroker, ribPolicies,
132 peerTracker, afiSafiType, pathSelectionStrategy);
135 private synchronized void init() {
136 final WriteTransaction tx = this.chain.newWriteOnlyTransaction();
137 tx.merge(LogicalDatastoreType.OPERATIONAL,
138 this.locRibTableIID.builder().child(Attributes.class).build(),
139 new AttributesBuilder().setUptodate(true).build());
140 tx.commit().addCallback(new FutureCallback<CommitInfo>() {
142 public void onSuccess(final CommitInfo result) {
143 LOG.trace("Successful commit");
147 public void onFailure(final Throwable trw) {
148 LOG.error("Failed commit", trw);
150 }, MoreExecutors.directExecutor());
152 final InstanceIdentifier<Tables> tableId = this.ribIId.builder().child(Peer.class)
153 .child(EffectiveRibIn.class).child(Tables.class, getTableKey()).build();
154 this.reg = this.dataBroker.registerDataTreeChangeListener(
155 new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, tableId), this);
159 * Re-initialize this LocRibWriter with new transaction chain.
161 * @param newChain new transaction chain
163 synchronized void restart(final @NonNull BindingTransactionChain newChain) {
164 requireNonNull(newChain);
166 this.chain = newChain;
171 public synchronized void close() {
172 if (this.reg != null) {
176 if (this.chain != null) {
182 private @NonNull RouteEntry<C, S, R, I> createEntry(final String routeId) {
183 final RouteEntry<C, S, R, I> ret = this.pathSelectionMode.createRouteEntry();
184 this.routeEntries.put(routeId, ret);
185 this.totalPrefixesCounter.increment();
186 LOG.trace("Created new entry for {}", routeId);
191 * We use two-stage processing here in hopes that we avoid duplicate
192 * calculations when multiple peers have changed a particular entry.
194 * @param changes on supported table
197 @SuppressWarnings("checkstyle:illegalCatch")
198 public synchronized void onDataTreeChanged(final Collection<DataTreeModification<Tables>> changes) {
199 if (this.chain == null) {
200 LOG.trace("Chain closed, ignoring received data change {} to LocRib {}", changes, this);
203 LOG.trace("Received data change {} to LocRib {}", changes, this);
204 final WriteTransaction tx = this.chain.newWriteOnlyTransaction();
206 final Map<RouteUpdateKey, RouteEntry<C, S, R, I>> toUpdate = update(tx, changes);
208 if (!toUpdate.isEmpty()) {
209 walkThrough(tx, toUpdate.entrySet());
211 } catch (final Exception e) {
212 LOG.error("Failed to completely propagate updates {}, state is undefined", changes, e);
214 tx.commit().addCallback(new FutureCallback<CommitInfo>() {
216 public void onSuccess(final CommitInfo result) {
217 LOG.trace("Successful commit");
221 public void onFailure(final Throwable trw) {
222 LOG.error("Failed commit", trw);
224 }, MoreExecutors.directExecutor());
228 @SuppressWarnings("unchecked")
229 private Map<RouteUpdateKey, RouteEntry<C, S, R, I>> update(final WriteTransaction tx,
230 final Collection<DataTreeModification<Tables>> changes) {
231 final Map<RouteUpdateKey, RouteEntry<C, S, R, I>> ret = new HashMap<>();
232 for (final DataTreeModification<Tables> tc : changes) {
233 final DataObjectModification<Tables> table = tc.getRootNode();
234 final DataTreeIdentifier<Tables> rootPath = tc.getRootPath();
235 final KeyedInstanceIdentifier<Peer, PeerKey> peerKIid = (KeyedInstanceIdentifier<Peer, PeerKey>)
236 rootPath.getRootIdentifier().firstIdentifierOf(Peer.class);
237 final RouterId peerUuid = RouterId.forPeerId(peerKIid.getKey().getPeerId());
239 Initialize Peer with routes under loc rib
241 if (!this.routeEntries.isEmpty() && table.getDataBefore() == null) {
242 final org.opendaylight.protocol.bgp.rib.spi.Peer toPeer
243 = this.peerTracker.getPeer(peerKIid.getKey().getPeerId());
244 if (toPeer != null && toPeer.supportsTable(this.entryDep.getLocalTablesKey())) {
245 LOG.debug("Peer {} table has been created, inserting existent routes", toPeer.getPeerId());
246 final List<ActualBestPathRoutes<C, S, R, I>> routesToStore = new ArrayList<>();
247 for (final Entry<String, RouteEntry<C, S, R, I>> entry : this.routeEntries.entrySet()) {
248 final List<ActualBestPathRoutes<C, S, R, I>> filteredRoute = entry.getValue()
249 .actualBestPaths(this.ribSupport, new RouteEntryInfoImpl(toPeer, entry.getKey()));
250 routesToStore.addAll(filteredRoute);
252 toPeer.initializeRibOut(this.entryDep, routesToStore);
256 Process new routes from Peer
258 updateNodes(table, peerUuid, tx, ret);
263 private void updateNodes(final DataObjectModification<Tables> table, final RouterId peerUuid,
264 final WriteTransaction tx, final Map<RouteUpdateKey, RouteEntry<C, S, R, I>> routes) {
265 final DataObjectModification<Attributes> attUpdate = table.getModifiedChildContainer(Attributes.class);
266 if (attUpdate != null) {
267 final Attributes newAttValue = attUpdate.getDataAfter();
268 if (newAttValue != null) {
269 LOG.trace("Uptodate found for {}", newAttValue);
270 tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTableIID.child(Attributes.class), newAttValue);
274 final DataObjectModification<S> routesChangesContainer
275 = table.getModifiedChildContainer(ribSupport.routesCaseClass(), ribSupport.routesContainerClass());
276 if (routesChangesContainer != null) {
277 updateRoutesEntries(routesChangesContainer.getModifiedChildren(), peerUuid, routes);
281 private void updateRoutesEntries(final Collection<? extends DataObjectModification<?>> collection,
282 final RouterId routerId, final Map<RouteUpdateKey, RouteEntry<C, S, R, I>> routes) {
283 for (final DataObjectModification<? extends DataObject> route : collection) {
284 if (!(route.getIdentifier() instanceof InstanceIdentifier.IdentifiableItem)) {
285 LOG.debug("Route {} already deleted", route.getIdentifier());
288 final I routeListKey = (I) ((InstanceIdentifier.IdentifiableItem) route.getIdentifier()).getKey();
289 final String routeKey = ribSupport.extractRouteKey(routeListKey);
290 final PathId pathId = ribSupport.extractPathId(routeListKey);
292 RouteEntry<C, S, R, I> entry;
293 switch (route.getModificationType()) {
295 entry = this.routeEntries.get(routeKey);
297 this.totalPathsCounter.decrement();
298 if (entry.removeRoute(routerId, pathId.getValue())) {
299 this.routeEntries.remove(routeKey);
300 this.totalPrefixesCounter.decrement();
301 LOG.trace("Removed route from {}", routerId);
305 case SUBTREE_MODIFIED:
307 final R newRoute = (R) route.getDataAfter();
308 entry = this.routeEntries.get(routeKey);
310 entry = createEntry(routeKey);
313 entry.addRoute(routerId, pathId.getValue(), newRoute);
314 this.totalPathsCounter.increment();
317 throw new IllegalStateException("Unhandled route modification " + route);
320 final RouteUpdateKey routeUpdateKey = new RouteUpdateKey(routerId, routeKey);
321 LOG.debug("Updated route {} entry {}", routeKey, entry);
322 routes.put(routeUpdateKey, entry);
326 private void walkThrough(final WriteTransaction tx,
327 final Set<Entry<RouteUpdateKey, RouteEntry<C, S, R, I>>> toUpdate) {
328 final List<StaleBestPathRoute<C, S, R, I>> staleRoutes = new ArrayList<>();
329 final List<AdvertizedRoute<C, S, R, I>> newRoutes = new ArrayList<>();
330 for (final Entry<RouteUpdateKey, RouteEntry<C, S, R, I>> e : toUpdate) {
331 LOG.trace("Walking through {}", e);
332 final RouteEntry<C, S, R, I> entry = e.getValue();
334 if (!entry.selectBest(this.ourAs)) {
335 LOG.trace("Best path has not changed, continuing");
339 entry.removeStalePaths(this.ribSupport, e.getKey().getRouteId()).ifPresent(staleRoutes::add);
340 newRoutes.addAll(entry.newBestPaths(this.ribSupport, e.getKey().getRouteId()));
342 updateLocRib(newRoutes, staleRoutes, tx);
343 this.peerTracker.getNonInternalPeers().parallelStream().forEach(
344 toPeer -> toPeer.refreshRibOut(this.entryDep, staleRoutes, newRoutes));
347 private void updateLocRib(final List<AdvertizedRoute<C, S, R, I>> newRoutes,
348 final List<StaleBestPathRoute<C, S, R, I>> staleRoutes,
349 final WriteTransaction tx) {
350 final KeyedInstanceIdentifier<Tables, TablesKey> locRibTarget = this.entryDep.getLocRibTableTarget();
352 for (final StaleBestPathRoute<C, S, R, I> staleContainer : staleRoutes) {
353 for (final I routeId : staleContainer.getStaleRouteKeyIdentifiers()) {
354 final InstanceIdentifier<R> routeTarget = ribSupport.createRouteIdentifier(locRibTarget, routeId);
355 LOG.debug("Delete route from LocRib {}", routeTarget);
356 tx.delete(LogicalDatastoreType.OPERATIONAL, routeTarget);
360 for (final AdvertizedRoute<C,S,R,I> advRoute : newRoutes) {
361 final R route = advRoute.getRoute();
362 final I iid = advRoute.getAddPathRouteKeyIdentifier();
363 final InstanceIdentifier<R> locRibRouteTarget
364 = this.ribSupport.createRouteIdentifier(locRibTarget, iid);
365 LOG.debug("Write route to LocRib {}", route);
366 tx.put(LogicalDatastoreType.OPERATIONAL, locRibRouteTarget, route);
371 public long getPrefixesCount() {
372 return this.totalPrefixesCounter.longValue();
376 public long getPathsCount() {
377 return this.totalPathsCounter.longValue();
380 TablesKey getTableKey() {
381 return this.ribSupport.getTablesKey();
385 public synchronized void refreshTable(final TablesKey tk, final PeerId peerId) {
386 final org.opendaylight.protocol.bgp.rib.spi.Peer toPeer = this.peerTracker.getPeer(peerId);
387 if (toPeer != null && toPeer.supportsTable(this.entryDep.getLocalTablesKey())) {
388 LOG.debug("Peer {} table has been created, inserting existent routes", toPeer.getPeerId());
389 final List<ActualBestPathRoutes<C, S, R, I>> routesToStore = new ArrayList<>();
390 for (final Entry<String, RouteEntry<C, S, R, I>> entry : this.routeEntries.entrySet()) {
391 final List<ActualBestPathRoutes<C, S, R, I>> filteredRoute = entry.getValue()
392 .actualBestPaths(this.ribSupport, new RouteEntryInfoImpl(toPeer, entry.getKey()));
393 routesToStore.addAll(filteredRoute);
395 toPeer.reEvaluateAdvertizement(this.entryDep, routesToStore);