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.mdsal.binding.api.ClusteredDataTreeChangeListener;
25 import org.opendaylight.mdsal.binding.api.DataBroker;
26 import org.opendaylight.mdsal.binding.api.DataObjectModification;
27 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
28 import org.opendaylight.mdsal.binding.api.DataTreeModification;
29 import org.opendaylight.mdsal.binding.api.TransactionChain;
30 import org.opendaylight.mdsal.binding.api.WriteTransaction;
31 import org.opendaylight.mdsal.common.api.CommitInfo;
32 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
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.rev200120.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.opendaylight.yangtools.yang.common.Uint32;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
73 // This class is NOT thread-safe
74 final class LocRibWriter<C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
75 R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>>
76 implements AutoCloseable, RibOutRefresh, TotalPrefixesCounter, TotalPathsCounter,
77 ClusteredDataTreeChangeListener<Tables> {
79 private static final Logger LOG = LoggerFactory.getLogger(LocRibWriter.class);
81 private final Map<String, RouteEntry<C, S, R, I>> routeEntries = new HashMap<>();
82 private final long ourAs;
83 private final RIBSupport<C, S, R, I> ribSupport;
84 private final DataBroker dataBroker;
85 private final PathSelectionMode pathSelectionMode;
86 private final LongAdder totalPathsCounter = new LongAdder();
87 private final LongAdder totalPrefixesCounter = new LongAdder();
88 private final RouteEntryDependenciesContainerImpl entryDep;
89 private final BGPPeerTracker peerTracker;
90 private final KeyedInstanceIdentifier<Rib, RibKey> ribIId;
91 private final KeyedInstanceIdentifier<Tables, TablesKey> locRibTableIID;
93 private TransactionChain chain;
95 private ListenerRegistration<?> reg;
97 private LocRibWriter(final RIBSupport<C, S, R, I> ribSupport,
98 final TransactionChain chain,
99 final KeyedInstanceIdentifier<Rib, RibKey> ribIId,
101 final DataBroker dataBroker,
102 final BGPRibRoutingPolicy ribPolicies,
103 final BGPPeerTracker peerTracker,
104 final Class<? extends AfiSafiType> afiSafiType,
105 final PathSelectionMode pathSelectionMode) {
106 this.chain = requireNonNull(chain);
107 this.ribIId = requireNonNull(ribIId);
108 this.ribSupport = requireNonNull(ribSupport);
109 this.locRibTableIID = ribIId.child(LocRib.class).child(Tables.class, ribSupport.getTablesKey());
110 this.ourAs = ourAs.toJava();
111 this.dataBroker = requireNonNull(dataBroker);
112 this.peerTracker = peerTracker;
113 this.pathSelectionMode = pathSelectionMode;
115 this.entryDep = new RouteEntryDependenciesContainerImpl(this.ribSupport, this.peerTracker, ribPolicies,
116 afiSafiType, this.locRibTableIID);
120 public static <C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>,
121 R extends Route & ChildOf<? super S> & Identifiable<I>, I extends Identifier<R>>
122 LocRibWriter<C, S, R, I> create(
123 final @NonNull RIBSupport<C, S, R, I> ribSupport,
124 final @NonNull Class<? extends AfiSafiType> afiSafiType,
125 final @NonNull TransactionChain chain,
126 final @NonNull KeyedInstanceIdentifier<Rib, RibKey> ribIId,
127 final @NonNull AsNumber ourAs,
128 final @NonNull DataBroker dataBroker,
129 final BGPRibRoutingPolicy ribPolicies,
130 final @NonNull BGPPeerTracker peerTracker,
131 final @NonNull PathSelectionMode pathSelectionStrategy) {
132 return new LocRibWriter<>(ribSupport, chain, ribIId, ourAs.getValue(), dataBroker, ribPolicies,
133 peerTracker, afiSafiType, pathSelectionStrategy);
136 private synchronized void init() {
137 final WriteTransaction tx = this.chain.newWriteOnlyTransaction();
138 tx.merge(LogicalDatastoreType.OPERATIONAL,
139 this.locRibTableIID.builder().child(Attributes.class).build(),
140 new AttributesBuilder().setUptodate(true).build());
141 tx.commit().addCallback(new FutureCallback<CommitInfo>() {
143 public void onSuccess(final CommitInfo result) {
144 LOG.trace("Successful commit");
148 public void onFailure(final Throwable trw) {
149 LOG.error("Failed commit", trw);
151 }, MoreExecutors.directExecutor());
153 final InstanceIdentifier<Tables> tableId = this.ribIId.builder().child(Peer.class)
154 .child(EffectiveRibIn.class).child(Tables.class, getTableKey()).build();
155 this.reg = this.dataBroker.registerDataTreeChangeListener(
156 DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, tableId), this);
160 * Re-initialize this LocRibWriter with new transaction chain.
162 * @param newChain new transaction chain
164 synchronized void restart(final @NonNull TransactionChain newChain) {
165 requireNonNull(newChain);
167 this.chain = newChain;
172 public synchronized void close() {
173 if (this.reg != null) {
177 if (this.chain != null) {
183 private @NonNull RouteEntry<C, S, R, I> createEntry(final String routeId) {
184 final RouteEntry<C, S, R, I> ret = this.pathSelectionMode.createRouteEntry();
185 this.routeEntries.put(routeId, ret);
186 this.totalPrefixesCounter.increment();
187 LOG.trace("Created new entry for {}", routeId);
192 * We use two-stage processing here in hopes that we avoid duplicate
193 * calculations when multiple peers have changed a particular entry.
195 * @param changes on supported table
198 @SuppressWarnings("checkstyle:illegalCatch")
199 public synchronized void onDataTreeChanged(final Collection<DataTreeModification<Tables>> changes) {
200 if (this.chain == null) {
201 LOG.trace("Chain closed, ignoring received data change {} to LocRib {}", changes, this);
204 LOG.trace("Received data change {} to LocRib {}", changes, this);
205 final WriteTransaction tx = this.chain.newWriteOnlyTransaction();
207 final Map<RouteUpdateKey, RouteEntry<C, S, R, I>> toUpdate = update(tx, changes);
209 if (!toUpdate.isEmpty()) {
210 walkThrough(tx, toUpdate.entrySet());
212 } catch (final Exception e) {
213 LOG.error("Failed to completely propagate updates {}, state is undefined", changes, e);
215 tx.commit().addCallback(new FutureCallback<CommitInfo>() {
217 public void onSuccess(final CommitInfo result) {
218 LOG.trace("Successful commit");
222 public void onFailure(final Throwable trw) {
223 LOG.error("Failed commit", trw);
225 }, MoreExecutors.directExecutor());
229 @SuppressWarnings("unchecked")
230 private Map<RouteUpdateKey, RouteEntry<C, S, R, I>> update(final WriteTransaction tx,
231 final Collection<DataTreeModification<Tables>> changes) {
232 final Map<RouteUpdateKey, RouteEntry<C, S, R, I>> ret = new HashMap<>();
233 for (final DataTreeModification<Tables> tc : changes) {
234 final DataObjectModification<Tables> table = tc.getRootNode();
235 final DataTreeIdentifier<Tables> rootPath = tc.getRootPath();
236 final KeyedInstanceIdentifier<Peer, PeerKey> peerKIid = (KeyedInstanceIdentifier<Peer, PeerKey>)
237 rootPath.getRootIdentifier().firstIdentifierOf(Peer.class);
238 final RouterId peerUuid = RouterId.forPeerId(peerKIid.getKey().getPeerId());
240 Initialize Peer with routes under loc rib
242 if (!this.routeEntries.isEmpty() && table.getDataBefore() == null) {
243 final org.opendaylight.protocol.bgp.rib.spi.Peer toPeer
244 = this.peerTracker.getPeer(peerUuid.getPeerId());
245 if (toPeer != null && toPeer.supportsTable(this.entryDep.getLocalTablesKey())) {
246 LOG.debug("Peer {} table has been created, inserting existent routes", toPeer.getPeerId());
247 final List<ActualBestPathRoutes<C, S, R, I>> routesToStore = new ArrayList<>();
248 for (final Entry<String, RouteEntry<C, S, R, I>> entry : this.routeEntries.entrySet()) {
249 final List<ActualBestPathRoutes<C, S, R, I>> filteredRoute = entry.getValue()
250 .actualBestPaths(this.ribSupport, new RouteEntryInfoImpl(toPeer, entry.getKey()));
251 routesToStore.addAll(filteredRoute);
253 toPeer.initializeRibOut(this.entryDep, routesToStore);
257 Process new routes from Peer
259 updateNodes(table, peerUuid, tx, ret);
264 private void updateNodes(final DataObjectModification<Tables> table, final RouterId peerUuid,
265 final WriteTransaction tx, final Map<RouteUpdateKey, RouteEntry<C, S, R, I>> routes) {
266 final DataObjectModification<Attributes> attUpdate = table.getModifiedChildContainer(Attributes.class);
267 if (attUpdate != null) {
268 final Attributes newAttValue = attUpdate.getDataAfter();
269 if (newAttValue != null) {
270 LOG.trace("Uptodate found for {}", newAttValue);
271 tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTableIID.child(Attributes.class), newAttValue);
275 final DataObjectModification<S> routesChangesContainer
276 = table.getModifiedChildContainer(ribSupport.routesCaseClass(), ribSupport.routesContainerClass());
277 if (routesChangesContainer != null) {
278 updateRoutesEntries(routesChangesContainer.getModifiedChildren(), peerUuid, routes);
282 private void updateRoutesEntries(final Collection<? extends DataObjectModification<?>> collection,
283 final RouterId routerId, final Map<RouteUpdateKey, RouteEntry<C, S, R, I>> routes) {
284 for (final DataObjectModification<? extends DataObject> route : collection) {
285 if (!(route.getIdentifier() instanceof InstanceIdentifier.IdentifiableItem)) {
286 LOG.debug("Route {} already deleted", route.getIdentifier());
289 final I routeListKey = (I) ((InstanceIdentifier.IdentifiableItem) route.getIdentifier()).getKey();
290 final String routeKey = ribSupport.extractRouteKey(routeListKey);
291 final PathId pathId = ribSupport.extractPathId(routeListKey);
293 RouteEntry<C, S, R, I> entry;
294 switch (route.getModificationType()) {
296 entry = this.routeEntries.get(routeKey);
298 this.totalPathsCounter.decrement();
299 if (entry.removeRoute(routerId, pathId.getValue())) {
300 this.routeEntries.remove(routeKey);
301 this.totalPrefixesCounter.decrement();
302 LOG.trace("Removed route from {}", routerId);
306 case SUBTREE_MODIFIED:
308 final R newRoute = (R) route.getDataAfter();
309 entry = this.routeEntries.get(routeKey);
311 entry = createEntry(routeKey);
314 entry.addRoute(routerId, pathId.getValue(), newRoute);
315 this.totalPathsCounter.increment();
318 throw new IllegalStateException("Unhandled route modification " + route);
321 final RouteUpdateKey routeUpdateKey = new RouteUpdateKey(routerId, routeKey);
322 LOG.debug("Updated route {} entry {}", routeKey, entry);
323 routes.put(routeUpdateKey, entry);
327 private void walkThrough(final WriteTransaction tx,
328 final Set<Entry<RouteUpdateKey, RouteEntry<C, S, R, I>>> toUpdate) {
329 final List<StaleBestPathRoute<C, S, R, I>> staleRoutes = new ArrayList<>();
330 final List<AdvertizedRoute<C, S, R, I>> newRoutes = new ArrayList<>();
331 for (final Entry<RouteUpdateKey, RouteEntry<C, S, R, I>> e : toUpdate) {
332 LOG.trace("Walking through {}", e);
333 final RouteEntry<C, S, R, I> entry = e.getValue();
335 if (!entry.selectBest(this.ourAs)) {
336 LOG.trace("Best path has not changed, continuing");
340 entry.removeStalePaths(this.ribSupport, e.getKey().getRouteId()).ifPresent(staleRoutes::add);
341 newRoutes.addAll(entry.newBestPaths(this.ribSupport, e.getKey().getRouteId()));
343 updateLocRib(newRoutes, staleRoutes, tx);
344 this.peerTracker.getNonInternalPeers().parallelStream().forEach(
345 toPeer -> toPeer.refreshRibOut(this.entryDep, staleRoutes, newRoutes));
348 private void updateLocRib(final List<AdvertizedRoute<C, S, R, I>> newRoutes,
349 final List<StaleBestPathRoute<C, S, R, I>> staleRoutes,
350 final WriteTransaction tx) {
351 final KeyedInstanceIdentifier<Tables, TablesKey> locRibTarget = this.entryDep.getLocRibTableTarget();
353 for (final StaleBestPathRoute<C, S, R, I> staleContainer : staleRoutes) {
354 for (final I routeId : staleContainer.getStaleRouteKeyIdentifiers()) {
355 final InstanceIdentifier<R> routeTarget = ribSupport.createRouteIdentifier(locRibTarget, routeId);
356 LOG.debug("Delete route from LocRib {}", routeTarget);
357 tx.delete(LogicalDatastoreType.OPERATIONAL, routeTarget);
361 for (final AdvertizedRoute<C,S,R,I> advRoute : newRoutes) {
362 final R route = advRoute.getRoute();
363 final I iid = advRoute.getAddPathRouteKeyIdentifier();
364 final InstanceIdentifier<R> locRibRouteTarget
365 = this.ribSupport.createRouteIdentifier(locRibTarget, iid);
366 LOG.debug("Write route to LocRib {}", route);
367 tx.put(LogicalDatastoreType.OPERATIONAL, locRibRouteTarget, route);
372 public long getPrefixesCount() {
373 return this.totalPrefixesCounter.longValue();
377 public long getPathsCount() {
378 return this.totalPathsCounter.longValue();
381 TablesKey getTableKey() {
382 return this.ribSupport.getTablesKey();
386 public synchronized void refreshTable(final TablesKey tk, final PeerId peerId) {
387 final org.opendaylight.protocol.bgp.rib.spi.Peer toPeer = this.peerTracker.getPeer(peerId);
388 if (toPeer != null && toPeer.supportsTable(this.entryDep.getLocalTablesKey())) {
389 LOG.debug("Peer {} table has been created, inserting existent routes", toPeer.getPeerId());
390 final List<ActualBestPathRoutes<C, S, R, I>> routesToStore = new ArrayList<>();
391 for (final Entry<String, RouteEntry<C, S, R, I>> entry : this.routeEntries.entrySet()) {
392 final List<ActualBestPathRoutes<C, S, R, I>> filteredRoute = entry.getValue()
393 .actualBestPaths(this.ribSupport, new RouteEntryInfoImpl(toPeer, entry.getKey()));
394 routesToStore.addAll(filteredRoute);
396 toPeer.reEvaluateAdvertizement(this.entryDep, routesToStore);