2 * Copyright (c) 2013 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.bgpcep.bgp.topology.provider;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Preconditions;
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.Collections;
19 import java.util.concurrent.atomic.AtomicBoolean;
20 import javax.annotation.concurrent.GuardedBy;
21 import org.opendaylight.bgpcep.topology.TopologyReference;
22 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
23 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
24 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
25 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
26 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
27 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
28 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
29 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
30 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
31 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
32 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
33 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
34 import org.opendaylight.mdsal.common.api.CommitInfo;
35 import org.opendaylight.protocol.bgp.rib.RibReference;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.Route;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.LocRib;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.AddressFamily;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.SubsequentAddressFamily;
42 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
44 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
45 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
46 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
47 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.TopologyTypes;
48 import org.opendaylight.yangtools.concepts.ListenerRegistration;
49 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 public abstract class AbstractTopologyBuilder<T extends Route> implements ClusteredDataTreeChangeListener<T>,
54 TopologyReference, TransactionChainListener {
55 private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologyBuilder.class);
56 // we limit the listener reset interval to be 5 min at most
57 private static final long LISTENER_RESET_LIMIT_IN_MILLSEC = 5 * 60 * 1000;
58 private static final int LISTENER_RESET_ENFORCE_COUNTER = 3;
59 private final InstanceIdentifier<Topology> topology;
60 private final RibReference locRibReference;
61 private final DataBroker dataProvider;
62 private final Class<? extends AddressFamily> afi;
63 private final Class<? extends SubsequentAddressFamily> safi;
64 private final TopologyKey topologyKey;
65 private final TopologyTypes topologyTypes;
66 private final long listenerResetLimitInMillsec;
67 private final int listenerResetEnforceCounter;
70 private ListenerRegistration<AbstractTopologyBuilder<T>> listenerRegistration = null;
72 private BindingTransactionChain chain = null;
73 private AtomicBoolean closed = new AtomicBoolean(false);
76 protected long listenerScheduledRestartTime = 0;
79 protected int listenerScheduledRestartEnforceCounter = 0;
81 protected AbstractTopologyBuilder(final DataBroker dataProvider, final RibReference locRibReference,
82 final TopologyId topologyId, final TopologyTypes types, final Class<? extends AddressFamily> afi,
83 final Class<? extends SubsequentAddressFamily> safi, final long listenerResetLimitInMillsec,
84 final int listenerResetEnforceCounter) {
85 this.dataProvider = dataProvider;
86 this.locRibReference = requireNonNull(locRibReference);
87 this.topologyKey = new TopologyKey(requireNonNull(topologyId));
88 this.topologyTypes = types;
91 this.listenerResetLimitInMillsec = listenerResetLimitInMillsec;
92 this.listenerResetEnforceCounter = listenerResetEnforceCounter;
93 this.topology = InstanceIdentifier.builder(NetworkTopology.class)
94 .child(Topology.class, this.topologyKey).build();
97 protected AbstractTopologyBuilder(final DataBroker dataProvider, final RibReference locRibReference,
98 final TopologyId topologyId, final TopologyTypes types, final Class<? extends AddressFamily> afi,
99 final Class<? extends SubsequentAddressFamily> safi) {
100 this(dataProvider, locRibReference, topologyId, types, afi, safi, LISTENER_RESET_LIMIT_IN_MILLSEC,
101 LISTENER_RESET_ENFORCE_COUNTER);
104 public final synchronized void start() {
105 LOG.debug("Initiating topology builder from {} at {}. AFI={}, SAFI={}", this.locRibReference, this.topology,
106 this.afi, this.safi);
107 initTransactionChain();
108 initOperationalTopology();
109 registerDataChangeListener();
113 * Register to data tree change listener.
115 private synchronized void registerDataChangeListener() {
116 Preconditions.checkState(this.listenerRegistration == null,
117 "Topology Listener on topology %s has been registered before.",
118 this.getInstanceIdentifier());
119 final InstanceIdentifier<Tables> tablesId = this.locRibReference.getInstanceIdentifier()
120 .child(LocRib.class).child(Tables.class, new TablesKey(this.afi, this.safi));
121 final DataTreeIdentifier<T> id = new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL,
122 getRouteWildcard(tablesId));
124 this.listenerRegistration = this.dataProvider.registerDataTreeChangeListener(id, this);
125 LOG.debug("Registered listener {} on topology {}. Timestamp={}", this, this.getInstanceIdentifier(),
126 this.listenerScheduledRestartTime);
130 * Unregister to data tree change listener.
132 private synchronized void unregisterDataChangeListener() {
133 if (this.listenerRegistration != null) {
134 LOG.debug("Unregistered listener {} on topology {}", this, this.getInstanceIdentifier());
135 this.listenerRegistration.close();
136 this.listenerRegistration = null;
140 protected abstract InstanceIdentifier<T> getRouteWildcard(InstanceIdentifier<Tables> tablesId);
142 protected abstract void createObject(ReadWriteTransaction trans, InstanceIdentifier<T> id, T value);
144 protected abstract void removeObject(ReadWriteTransaction trans, InstanceIdentifier<T> id, T value);
146 protected abstract void clearTopology();
149 public final InstanceIdentifier<Topology> getInstanceIdentifier() {
150 return this.topology;
153 public final synchronized FluentFuture<? extends CommitInfo> close() {
154 if (this.closed.getAndSet(true)) {
155 LOG.trace("Transaction chain was already closed.");
156 return CommitInfo.emptyFluentFuture();
158 LOG.info("Shutting down builder for {}", getInstanceIdentifier());
159 unregisterDataChangeListener();
160 final FluentFuture<? extends CommitInfo> future = destroyOperationalTopology();
161 destroyTransactionChain();
166 @SuppressWarnings("checkstyle:IllegalCatch")
167 public synchronized void onDataTreeChanged(final Collection<DataTreeModification<T>> changes) {
168 if (this.closed.get()) {
169 LOG.trace("Transaction chain was already closed, skipping update.");
172 // check if the transaction chain needed to be restarted due to a previous error
173 if (restartTransactionChainOnDemand()) {
174 LOG.debug("The data change {} is disregarded due to restart of listener {}", changes, this);
177 final ReadWriteTransaction trans = this.chain.newReadWriteTransaction();
178 LOG.trace("Received data change {} event with transaction {}", changes, trans.getIdentifier());
179 final AtomicBoolean transactionInError = new AtomicBoolean(false);
180 for (final DataTreeModification<T> change : changes) {
182 routeChanged(change, trans);
183 } catch (final RuntimeException exc) {
184 LOG.warn("Data change {} (transaction {}) was not completely propagated to listener {}", change,
185 trans.getIdentifier(), this, exc);
186 // trans.cancel() is not supported by PingPongTransactionChain, so we just skip the problematic change
187 // trans.commit() must be called first to unlock the current transaction chain, to make the chain
188 // closable so we cannot exit the #onDataTreeChanged() yet
189 transactionInError.set(true);
193 trans.commit().addCallback(new FutureCallback<CommitInfo>() {
195 public void onSuccess(final CommitInfo result) {
196 // as we are enforcing trans.commit(), in some cases the transaction execution actually could be
197 // successfully even when an exception is captured, thus #onTransactionChainFailed() never get invoked.
198 // Though the transaction chain remains usable,
199 // the data loss will not be able to be recovered. Thus we schedule a listener restart here
200 if (transactionInError.get()) {
201 LOG.warn("Transaction {} committed successfully while exception captured. Rescheduling a restart"
202 + " of listener {}", trans
203 .getIdentifier(), AbstractTopologyBuilder.this);
204 scheduleListenerRestart();
206 LOG.trace("Transaction {} committed successfully", trans.getIdentifier());
211 public void onFailure(final Throwable throwable) {
212 // we do nothing but print out the log. Transaction chain restart will be done in
213 // #onTransactionChainFailed()
214 LOG.error("Failed to propagate change (transaction {}) by listener {}", trans.getIdentifier(),
215 AbstractTopologyBuilder.this, throwable);
217 }, MoreExecutors.directExecutor());
221 protected void routeChanged(final DataTreeModification<T> change, final ReadWriteTransaction trans) {
222 final DataObjectModification<T> root = change.getRootNode();
223 switch (root.getModificationType()) {
225 removeObject(trans, change.getRootPath().getRootIdentifier(), root.getDataBefore());
227 case SUBTREE_MODIFIED:
229 if (root.getDataBefore() != null) {
230 removeObject(trans, change.getRootPath().getRootIdentifier(), root.getDataBefore());
232 createObject(trans, change.getRootPath().getRootIdentifier(), root.getDataAfter());
235 throw new IllegalArgumentException("Unhandled modification type " + root.getModificationType());
239 private synchronized void initOperationalTopology() {
240 requireNonNull(this.chain, "A valid transaction chain must be provided.");
241 final WriteTransaction trans = this.chain.newWriteOnlyTransaction();
242 trans.put(LogicalDatastoreType.OPERATIONAL, this.topology,
243 new TopologyBuilder().setKey(this.topologyKey).setServerProvided(Boolean.TRUE)
244 .setTopologyTypes(this.topologyTypes)
245 .setLink(Collections.emptyList()).setNode(Collections.emptyList()).build(), true);
246 trans.commit().addCallback(new FutureCallback<CommitInfo>() {
248 public void onSuccess(final CommitInfo result) {
249 LOG.trace("Transaction {} committed successfully", trans.getIdentifier());
253 public void onFailure(final Throwable throwable) {
254 LOG.error("Failed to initialize topology {} (transaction {}) by listener {}",
255 AbstractTopologyBuilder.this.topology,
256 trans.getIdentifier(), AbstractTopologyBuilder.this, throwable);
258 }, MoreExecutors.directExecutor());
262 * Destroy the current operational topology data. Note a valid transaction must be provided.
264 private synchronized FluentFuture<? extends CommitInfo> destroyOperationalTopology() {
265 requireNonNull(this.chain, "A valid transaction chain must be provided.");
266 final WriteTransaction trans = this.chain.newWriteOnlyTransaction();
267 trans.delete(LogicalDatastoreType.OPERATIONAL, getInstanceIdentifier());
268 final FluentFuture<? extends CommitInfo> future = trans.commit();
269 future.addCallback(new FutureCallback<CommitInfo>() {
271 public void onSuccess(final CommitInfo result) {
272 LOG.trace("Operational topology removed {}", AbstractTopologyBuilder.this.topology);
276 public void onFailure(final Throwable throwable) {
277 LOG.error("Unable to reset operational topology {} (transaction {})",
278 AbstractTopologyBuilder.this.topology, trans.getIdentifier(), throwable);
280 }, MoreExecutors.directExecutor());
286 * Reset a transaction chain by closing the current chain and starting a new one.
288 private synchronized void initTransactionChain() {
289 LOG.debug("Initializing transaction chain for topology {}", this);
290 Preconditions.checkState(this.chain == null,
291 "Transaction chain has to be closed before being initialized");
292 this.chain = this.dataProvider.createTransactionChain(this);
296 * Destroy the current transaction chain.
298 private synchronized void destroyTransactionChain() {
299 if (this.chain != null) {
300 LOG.debug("Destroy transaction chain for topology {}", this);
301 // we cannot close the transaction chain, as it will close the AbstractDOMForwardedTransactionFactory
302 // and the transaction factory cannot be reopen even if we recreate the transaction chain
303 // so we abandon the chain directly
304 // FIXME we want to close the transaction chain gracefully once the PingPongTransactionChain get improved
305 // and the above problem get resolved.
307 // this.chain.close();
308 // } catch (Exception e) {
309 // // the close() may not succeed when the transaction chain is locked
310 // LOG.error("Unable to close transaction chain {} for topology builder {}", this.chain,
311 // getInstanceIdentifier());
318 * Reset the data change listener to its initial status.
319 * By resetting the listener we will be able to recover all the data lost before
322 protected synchronized void resetListener() {
323 requireNonNull(this.listenerRegistration, "Listener on topology " + this + " hasn't been initialized.");
324 LOG.debug("Resetting data change listener for topology builder {}", getInstanceIdentifier());
325 // unregister current listener to prevent incoming data tree change first
326 unregisterDataChangeListener();
327 // create new transaction chain to reset the chain status
328 resetTransactionChain();
329 // reset the operational topology data so that we can have clean status
330 destroyOperationalTopology();
331 initOperationalTopology();
332 // re-register the data change listener to reset the operational topology
333 // we are expecting to receive all the pre-exist route change on the next onDataTreeChanged() call
334 registerDataChangeListener();
338 * Reset the transaction chain only so that the PingPong transaction chain will become usable again.
339 * However, there will be data loss if we do not apply the previous failed transaction again
342 protected synchronized void resetTransactionChain() {
343 LOG.debug("Resetting transaction chain for topology builder {}", getInstanceIdentifier());
344 destroyTransactionChain();
345 initTransactionChain();
349 * There are a few reasons we want to schedule a listener restart in a delayed manner:
350 * 1. we should avoid restarting the listener as when the topology is big, there might be huge overhead
351 * rebuilding the whole linkstate topology again and again
352 * 2. the #onTransactionChainFailed() normally get invoked after a delay. During that time gap, more
353 * data changes might still be pushed to #onDataTreeChanged(). And because #onTransactionChainFailed()
354 * is not invoked yet, listener restart/transaction chain restart is not done. Thus the new changes
355 * will still cause error and another #onTransactionChainFailed() might be invoked later. The listener
356 * will be restarted again in that case, which is unexpected. Restarting of transaction chain only introduce
357 * little overhead and it's okay to be restarted within a small time window.
358 * Note: when the listener is restarted, we can disregard all the incoming data changes before the restart is
359 * done, as after the listener unregister/reregister, the first #onDataTreeChanged() call will contain the a
360 * complete set of existing changes
362 * @return if the listener get restarted, return true; otherwise false
365 protected synchronized boolean restartTransactionChainOnDemand() {
366 if (this.listenerScheduledRestartTime > 0) {
367 // when the #this.listenerScheduledRestartTime timer timed out we can reset the listener,
368 // otherwise we should only reset the transaction chain
369 if (System.currentTimeMillis() > this.listenerScheduledRestartTime) {
370 // reset the the restart timer
371 this.listenerScheduledRestartTime = 0;
372 this.listenerScheduledRestartEnforceCounter = 0;
377 resetTransactionChain();
383 protected synchronized void scheduleListenerRestart() {
384 if (0 == this.listenerScheduledRestartTime) {
385 this.listenerScheduledRestartTime = System.currentTimeMillis() + this.listenerResetLimitInMillsec;
386 } else if (System.currentTimeMillis() > this.listenerScheduledRestartTime
387 && ++this.listenerScheduledRestartEnforceCounter < this.listenerResetEnforceCounter) {
388 // if the transaction failure happens again, we will delay the listener restart up to
389 // #LISTENER_RESET_LIMIT_IN_MILLSEC times
390 this.listenerScheduledRestartTime += this.listenerResetLimitInMillsec;
392 LOG.debug("A listener restart was scheduled at {} (current system time is {})",
393 this.listenerScheduledRestartTime, System.currentTimeMillis());
397 public final synchronized void onTransactionChainFailed(final TransactionChain<?, ?> transactionChain,
398 final AsyncTransaction<?, ?> transaction, final Throwable cause) {
399 LOG.error("Topology builder for {} failed in transaction {}.", getInstanceIdentifier(),
400 transaction != null ? transaction.getIdentifier() : null, cause);
401 scheduleListenerRestart();
402 restartTransactionChainOnDemand();
406 public final void onTransactionChainSuccessful(final TransactionChain<?, ?> transactionChain) {
407 LOG.info("Topology builder for {} shut down", getInstanceIdentifier());