YANG revision dates mass-update
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / LocRibWriter.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.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;
18 import java.util.Map;
19 import java.util.Map.Entry;
20 import java.util.Set;
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;
72
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> {
78
79     private static final Logger LOG = LoggerFactory.getLogger(LocRibWriter.class);
80
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;
92
93     private TransactionChain chain;
94     @GuardedBy("this")
95     private ListenerRegistration<?> reg;
96
97     private LocRibWriter(final RIBSupport<C, S, R, I> ribSupport,
98             final TransactionChain chain,
99             final KeyedInstanceIdentifier<Rib, RibKey> ribIId,
100             final Uint32 ourAs,
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;
114
115         this.entryDep = new RouteEntryDependenciesContainerImpl(this.ribSupport, this.peerTracker, ribPolicies,
116                 afiSafiType, this.locRibTableIID);
117         init();
118     }
119
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);
134     }
135
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>() {
142             @Override
143             public void onSuccess(final CommitInfo result) {
144                 LOG.trace("Successful commit");
145             }
146
147             @Override
148             public void onFailure(final Throwable trw) {
149                 LOG.error("Failed commit", trw);
150             }
151         }, MoreExecutors.directExecutor());
152
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);
157     }
158
159     /**
160      * Re-initialize this LocRibWriter with new transaction chain.
161      *
162      * @param newChain new transaction chain
163      */
164     synchronized void restart(final @NonNull TransactionChain newChain) {
165         requireNonNull(newChain);
166         close();
167         this.chain = newChain;
168         init();
169     }
170
171     @Override
172     public synchronized void close() {
173         if (this.reg != null) {
174             this.reg.close();
175             this.reg = null;
176         }
177         if (this.chain != null) {
178             this.chain.close();
179             this.chain = null;
180         }
181     }
182
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);
188         return ret;
189     }
190
191     /**
192      * We use two-stage processing here in hopes that we avoid duplicate
193      * calculations when multiple peers have changed a particular entry.
194      *
195      * @param changes on supported table
196      */
197     @Override
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);
202             return;
203         }
204         LOG.trace("Received data change {} to LocRib {}", changes, this);
205         final WriteTransaction tx = this.chain.newWriteOnlyTransaction();
206         try {
207             final Map<RouteUpdateKey, RouteEntry<C, S, R, I>> toUpdate = update(tx, changes);
208
209             if (!toUpdate.isEmpty()) {
210                 walkThrough(tx, toUpdate.entrySet());
211             }
212         } catch (final Exception e) {
213             LOG.error("Failed to completely propagate updates {}, state is undefined", changes, e);
214         } finally {
215             tx.commit().addCallback(new FutureCallback<CommitInfo>() {
216                 @Override
217                 public void onSuccess(final CommitInfo result) {
218                     LOG.trace("Successful commit");
219                 }
220
221                 @Override
222                 public void onFailure(final Throwable trw) {
223                     LOG.error("Failed commit", trw);
224                 }
225             }, MoreExecutors.directExecutor());
226         }
227     }
228
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());
239             /*
240             Initialize Peer with routes under loc rib
241              */
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);
252                     }
253                     toPeer.initializeRibOut(this.entryDep, routesToStore);
254                 }
255             }
256             /*
257             Process new routes from Peer
258              */
259             updateNodes(table, peerUuid, tx, ret);
260         }
261         return ret;
262     }
263
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);
272             }
273         }
274
275         final DataObjectModification<S> routesChangesContainer
276                 = table.getModifiedChildContainer(ribSupport.routesCaseClass(), ribSupport.routesContainerClass());
277         if (routesChangesContainer != null) {
278             updateRoutesEntries(routesChangesContainer.getModifiedChildren(), peerUuid, routes);
279         }
280     }
281
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());
287                 return;
288             }
289             final I routeListKey = (I) ((InstanceIdentifier.IdentifiableItem) route.getIdentifier()).getKey();
290             final String routeKey = ribSupport.extractRouteKey(routeListKey);
291             final PathId pathId = ribSupport.extractPathId(routeListKey);
292
293             RouteEntry<C, S, R, I> entry;
294             switch (route.getModificationType()) {
295                 case DELETE:
296                     entry = this.routeEntries.get(routeKey);
297                     if (entry != null) {
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);
303                         }
304                     }
305                     break;
306                 case SUBTREE_MODIFIED:
307                 case WRITE:
308                     final R newRoute = (R) route.getDataAfter();
309                     entry = this.routeEntries.get(routeKey);
310                     if (entry == null) {
311                         entry = createEntry(routeKey);
312                     }
313
314                     entry.addRoute(routerId, pathId.getValue(), newRoute);
315                     this.totalPathsCounter.increment();
316                     break;
317                 default:
318                     throw new IllegalStateException("Unhandled route modification " + route);
319             }
320
321             final RouteUpdateKey routeUpdateKey = new RouteUpdateKey(routerId, routeKey);
322             LOG.debug("Updated route {} entry {}", routeKey, entry);
323             routes.put(routeUpdateKey, entry);
324         }
325     }
326
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();
334
335             if (!entry.selectBest(this.ourAs)) {
336                 LOG.trace("Best path has not changed, continuing");
337                 continue;
338             }
339
340             entry.removeStalePaths(this.ribSupport, e.getKey().getRouteId()).ifPresent(staleRoutes::add);
341             newRoutes.addAll(entry.newBestPaths(this.ribSupport, e.getKey().getRouteId()));
342         }
343         updateLocRib(newRoutes, staleRoutes, tx);
344         this.peerTracker.getNonInternalPeers().parallelStream().forEach(
345             toPeer -> toPeer.refreshRibOut(this.entryDep, staleRoutes, newRoutes));
346     }
347
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();
352
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);
358             }
359         }
360
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);
368         }
369     }
370
371     @Override
372     public long getPrefixesCount() {
373         return this.totalPrefixesCounter.longValue();
374     }
375
376     @Override
377     public long getPathsCount() {
378         return this.totalPathsCounter.longValue();
379     }
380
381     TablesKey getTableKey() {
382         return this.ribSupport.getTablesKey();
383     }
384
385     @Override
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);
395             }
396             toPeer.reEvaluateAdvertizement(this.entryDep, routesToStore);
397         }
398     }
399 }