BUG-7222: Make BGP DS clean up asynchronous
[bgpcep.git] / bgp / topology-provider / src / main / java / org / opendaylight / bgpcep / bgp / topology / provider / AbstractTopologyBuilder.java
1 /*
2  * Copyright (c) 2013 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.bgpcep.bgp.topology.provider;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.concurrent.atomic.AtomicBoolean;
19 import javax.annotation.concurrent.GuardedBy;
20 import org.opendaylight.bgpcep.topology.TopologyReference;
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.ReadWriteTransaction;
28 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
29 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
30 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
31 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
32 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
33 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
34 import org.opendaylight.protocol.bgp.rib.RibReference;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.Route;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.LocRib;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.AddressFamily;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.SubsequentAddressFamily;
41 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
42 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
44 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
45 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
46 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Link;
47 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
48 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.TopologyTypes;
49 import org.opendaylight.yangtools.concepts.ListenerRegistration;
50 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 public abstract class AbstractTopologyBuilder<T extends Route> implements ClusteredDataTreeChangeListener<T>,
55     TopologyReference, TransactionChainListener {
56     private static final Logger LOG = LoggerFactory.getLogger(AbstractTopologyBuilder.class);
57     // we limit the listener reset interval to be 5 min at most
58     private static final long LISTENER_RESET_LIMIT_IN_MILLSEC = 5 * 60 * 1000;
59     private static final int LISTENER_RESET_ENFORCE_COUNTER = 3;
60     private final InstanceIdentifier<Topology> topology;
61     private final RibReference locRibReference;
62     private final DataBroker dataProvider;
63     private final Class<? extends AddressFamily> afi;
64     private final Class<? extends SubsequentAddressFamily> safi;
65     private final TopologyKey topologyKey;
66     private final TopologyTypes topologyTypes;
67     private final long listenerResetLimitInMillsec;
68     private final int listenerResetEnforceCounter;
69
70     @GuardedBy("this")
71     private ListenerRegistration<AbstractTopologyBuilder<T>> listenerRegistration = null;
72     @GuardedBy("this")
73     private BindingTransactionChain chain = null;
74     @GuardedBy("this")
75     private boolean closed = false;
76     @GuardedBy("this")
77     @VisibleForTesting
78     protected long listenerScheduledRestartTime = 0;
79     @GuardedBy("this")
80     @VisibleForTesting
81     protected int listenerScheduledRestartEnforceCounter = 0;
82
83     protected AbstractTopologyBuilder(final DataBroker dataProvider, final RibReference locRibReference,
84             final TopologyId topologyId, final TopologyTypes types, final Class<? extends AddressFamily> afi,
85         final Class<? extends SubsequentAddressFamily> safi, final long listenerResetLimitInMillsec,
86         final int listenerResetEnforceCounter) {
87         this.dataProvider = dataProvider;
88         this.locRibReference = Preconditions.checkNotNull(locRibReference);
89         this.topologyKey = new TopologyKey(Preconditions.checkNotNull(topologyId));
90         this.topologyTypes = types;
91         this.afi = afi;
92         this.safi = safi;
93         this.listenerResetLimitInMillsec = listenerResetLimitInMillsec;
94         this.listenerResetEnforceCounter = listenerResetEnforceCounter;
95         this.topology = InstanceIdentifier.builder(NetworkTopology.class).child(Topology.class, this.topologyKey).build();
96     }
97
98     protected AbstractTopologyBuilder(final DataBroker dataProvider, final RibReference locRibReference,
99         final TopologyId topologyId, final TopologyTypes types, final Class<? extends AddressFamily> afi,
100         final Class<? extends SubsequentAddressFamily> safi) {
101         this(dataProvider, locRibReference, topologyId, types, afi, safi, LISTENER_RESET_LIMIT_IN_MILLSEC, LISTENER_RESET_ENFORCE_COUNTER);
102     }
103
104     public final synchronized void start() {
105         LOG.debug("Initiating topology builder from {} at {}. AFI={}, SAFI={}", this.locRibReference, this.topology, this.afi, this.safi);
106         initTransactionChain();
107         initOperationalTopology();
108         registerDataChangeListener();
109     }
110
111     @Deprecated
112     public final InstanceIdentifier<Tables> tableInstanceIdentifier(final Class<? extends AddressFamily> afi,
113             final Class<? extends SubsequentAddressFamily> safi) {
114         return this.locRibReference.getInstanceIdentifier().builder().child(LocRib.class).child(Tables.class, new TablesKey(afi, safi)).build();
115     }
116
117     /**
118      * Register to data tree change listener
119      */
120     private synchronized void registerDataChangeListener() {
121         Preconditions.checkState(this.listenerRegistration == null, "Topology Listener on topology %s has been registered before.", this.getInstanceIdentifier());
122         final InstanceIdentifier<Tables> tablesId = this.locRibReference.getInstanceIdentifier().child(LocRib.class).child(Tables.class, new TablesKey(this.afi, this.safi));
123         final DataTreeIdentifier<T> id = new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, getRouteWildcard(tablesId));
124
125         this.listenerRegistration = this.dataProvider.registerDataTreeChangeListener(id, this);
126         LOG.debug("Registered listener {} on topology {}. Timestamp={}", this, this.getInstanceIdentifier(), this.listenerScheduledRestartTime);
127     }
128
129     /**
130      * Unregister to data tree change listener
131      */
132     private final 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;
137         }
138     }
139
140     protected abstract InstanceIdentifier<T> getRouteWildcard(InstanceIdentifier<Tables> tablesId);
141
142     protected abstract void createObject(ReadWriteTransaction trans, InstanceIdentifier<T> id, T value);
143
144     protected abstract void removeObject(ReadWriteTransaction trans, InstanceIdentifier<T> id, T value);
145
146     protected abstract void clearTopology();
147
148     @Override
149     public final InstanceIdentifier<Topology> getInstanceIdentifier() {
150         return this.topology;
151     }
152
153     public final synchronized ListenableFuture<Void> close() {
154         if (this.closed) {
155             LOG.trace("Transaction chain was already closed.");
156             Futures.immediateFuture(null);
157         }
158         this.closed = true;
159         LOG.info("Shutting down builder for {}", getInstanceIdentifier());
160         unregisterDataChangeListener();
161         final ListenableFuture<Void> future = destroyOperationalTopology();
162         destroyTransactionChain();
163         return future;
164     }
165
166     @Override
167     public synchronized void onDataTreeChanged(final Collection<DataTreeModification<T>> changes) {
168         if (this.closed) {
169             LOG.trace("Transaction chain was already closed, skipping update.");
170             return;
171         }
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);
175             return;
176         }
177         final ReadWriteTransaction trans = this.chain.newReadWriteTransaction();
178         LOG.debug("Received data change {} event with transaction {}", changes, trans.getIdentifier());
179         final AtomicBoolean transactionInError = new AtomicBoolean(false);
180         for (final DataTreeModification<T> change : changes) {
181             try {
182                 routeChanged(change, trans);
183             } catch (final RuntimeException e) {
184                 LOG.warn("Data change {} (transaction {}) was not completely propagated to listener {}", change, trans.getIdentifier(), this, e);
185                 // trans.cancel() is not supported by PingPongTransactionChain, so we just skip the problematic change
186                 // trans.submit() must be called first to unlock the current transaction chain, to make the chain closable
187                 // so we cannot exit the #onDataTreeChanged() yet
188                 transactionInError.set(true);
189                 break;
190             }
191         }
192         Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
193             @Override
194             public void onSuccess(final Void result) {
195                 // as we are enforcing trans.submit(), in some cases the transaction execution actually could be successfully even when an
196                 // exception is captured, thus #onTransactionChainFailed() never get invoked. Though the transaction chain remains usable,
197                 // the data loss will not be able to be recovered. Thus we schedule a listener restart here
198                 if (transactionInError.get()) {
199                     LOG.warn("Transaction {} committed successfully while exception captured. Rescheduling a restart of listener {}", trans
200                         .getIdentifier(), AbstractTopologyBuilder.this);
201                     scheduleListenerRestart();
202                 } else {
203                     LOG.trace("Transaction {} committed successfully", trans.getIdentifier());
204                 }
205             }
206
207             @Override
208             public void onFailure(final Throwable t) {
209                 // we do nothing but print out the log. Transaction chain restart will be done in #onTransactionChainFailed()
210                 LOG.error("Failed to propagate change (transaction {}) by listener {}", trans.getIdentifier(), AbstractTopologyBuilder.this, t);
211             }
212         });
213     }
214
215     @VisibleForTesting
216     protected void routeChanged(final DataTreeModification<T> change, final ReadWriteTransaction trans) {
217         final DataObjectModification<T> root = change.getRootNode();
218         switch (root.getModificationType()) {
219         case DELETE:
220             removeObject(trans, change.getRootPath().getRootIdentifier(), root.getDataBefore());
221             break;
222         case SUBTREE_MODIFIED:
223         case WRITE:
224             if (root.getDataBefore() != null) {
225                 removeObject(trans, change.getRootPath().getRootIdentifier(), root.getDataBefore());
226             }
227             createObject(trans, change.getRootPath().getRootIdentifier(), root.getDataAfter());
228             break;
229         default:
230             throw new IllegalArgumentException("Unhandled modification type " + root.getModificationType());
231         }
232     }
233
234     private synchronized void initOperationalTopology() {
235         Preconditions.checkNotNull(this.chain, "A valid transaction chain must be provided.");
236         final WriteTransaction trans = this.chain.newWriteOnlyTransaction();
237         trans.put(LogicalDatastoreType.OPERATIONAL, this.topology,
238             new TopologyBuilder().setKey(this.topologyKey).setServerProvided(Boolean.TRUE).setTopologyTypes(this.topologyTypes)
239                                  .setLink(Collections.<Link>emptyList()).setNode(Collections.<Node>emptyList()).build(), true);
240         Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
241             @Override
242             public void onSuccess(final Void result) {
243                 LOG.trace("Transaction {} committed successfully", trans.getIdentifier());
244             }
245
246             @Override
247             public void onFailure(final Throwable t) {
248                 LOG.error("Failed to initialize topology {} (transaction {}) by listener {}", AbstractTopologyBuilder.this.topology,
249                     trans.getIdentifier(), AbstractTopologyBuilder.this, t);
250             }
251         });
252     }
253
254     /**
255      * Destroy the current operational topology data. Note a valid transaction must be provided
256      * @throws TransactionCommitFailedException
257      */
258     private synchronized ListenableFuture<Void> destroyOperationalTopology() {
259         Preconditions.checkNotNull(this.chain, "A valid transaction chain must be provided.");
260         final WriteTransaction trans = this.chain.newWriteOnlyTransaction();
261         trans.delete(LogicalDatastoreType.OPERATIONAL, getInstanceIdentifier());
262         final CheckedFuture<Void, TransactionCommitFailedException> future = trans.submit();
263         Futures.addCallback(future, new FutureCallback<Void>() {
264             @Override
265             public void onSuccess(final Void result) {
266                 LOG.trace("Operational topology removed {}", AbstractTopologyBuilder.this.topology);
267             }
268
269             @Override
270             public void onFailure(final Throwable t) {
271                 LOG.error("Unable to reset operational topology {} (transaction {})",
272                     AbstractTopologyBuilder.this.topology, trans.getIdentifier(), t);
273             }
274         });
275         clearTopology();
276         return future;
277     }
278
279     /**
280      * Reset a transaction chain by closing the current chain and starting a new one
281      */
282     private synchronized void initTransactionChain() {
283         LOG.debug("Initializing transaction chain for topology {}", this);
284         Preconditions.checkState(this.chain == null, "Transaction chain has to be closed before being initialized");
285         this.chain = this.dataProvider.createTransactionChain(this);
286     }
287
288     /**
289      * Destroy the current transaction chain
290      */
291     private synchronized void destroyTransactionChain() {
292         if (this.chain != null) {
293             LOG.debug("Destroy transaction chain for topology {}", this);
294             // we cannot close the transaction chain, as it will close the AbstractDOMForwardedTransactionFactory
295             // and the transaction factory cannot be reopen even if we recreate the transaction chain
296             // so we abandon the chain directly
297             // FIXME we want to close the transaction chain gracefully once the PingPongTransactionChain get improved
298             // and the above problem get resolved.
299 //            try {
300 //                this.chain.close();
301 //            } catch (Exception e) {
302 //                // the close() may not succeed when the transaction chain is locked
303 //                LOG.error("Unable to close transaction chain {} for topology builder {}", this.chain, getInstanceIdentifier());
304 //            }
305             this.chain = null;
306         }
307     }
308
309     /**
310      * Reset the data change listener to its initial status
311      * By resetting the listener we will be able to recover all the data lost before
312      */
313     @VisibleForTesting
314     protected synchronized void resetListener() {
315         Preconditions.checkNotNull(this.listenerRegistration, "Listener on topology %s hasn't been initialized.", this);
316         LOG.debug("Resetting data change listener for topology builder {}", getInstanceIdentifier());
317         // unregister current listener to prevent incoming data tree change first
318         unregisterDataChangeListener();
319         // create new transaction chain to reset the chain status
320         resetTransactionChain();
321         // reset the operational topology data so that we can have clean status
322         destroyOperationalTopology();
323         initOperationalTopology();
324         // re-register the data change listener to reset the operational topology
325         // we are expecting to receive all the pre-exist route change on the next onDataTreeChanged() call
326         registerDataChangeListener();
327     }
328
329     /**
330      * Reset the transaction chain only so that the PingPong transaction chain will become usable again.
331      * However, there will be data loss if we do not apply the previous failed transaction again
332      */
333     @VisibleForTesting
334     protected synchronized void resetTransactionChain() {
335         LOG.debug("Resetting transaction chain for topology builder {}", getInstanceIdentifier());
336         destroyTransactionChain();
337         initTransactionChain();
338     }
339
340     /**
341      * There are a few reasons we want to schedule a listener restart in a delayed manner:
342      * 1. we should avoid restarting the listener as when the topology is big, there might be huge overhead
343      *    rebuilding the whole linkstate topology again and again
344      * 2. the #onTransactionChainFailed() normally get invoked after a delay. During that time gap, more
345      *    data changes might still be pushed to #onDataTreeChanged(). And because #onTransactionChainFailed()
346      *    is not invoked yet, listener restart/transaction chain restart is not done. Thus the new changes
347      *    will still cause error and another #onTransactionChainFailed() might be invoked later. The listener
348      *    will be restarted again in that case, which is unexpected. Restarting of transaction chain only introduce
349      *    little overhead and it's okay to be restarted within a small time window
350      *
351      * Note: when the listener is restarted, we can disregard all the incoming data changes before the restart is
352      * done, as after the listener unregister/reregister, the first #onDataTreeChanged() call will contain the a
353      * complete set of existing changes
354      *
355      * @return if the listener get restarted, return true; otherwise false
356      */
357     @VisibleForTesting
358     protected synchronized boolean restartTransactionChainOnDemand() {
359         if (this.listenerScheduledRestartTime > 0) {
360             // when the #this.listenerScheduledRestartTime timer timed out we can reset the listener, otherwise we should only reset the transaction chain
361             if (System.currentTimeMillis() > this.listenerScheduledRestartTime) {
362                 // reset the the restart timer
363                 this.listenerScheduledRestartTime = 0;
364                 this.listenerScheduledRestartEnforceCounter = 0;
365                 resetListener();
366                 return true;
367             } else {
368                 resetTransactionChain();
369             }
370         }
371         return false;
372     }
373
374     @VisibleForTesting
375     protected synchronized void scheduleListenerRestart() {
376         if (0 == this.listenerScheduledRestartTime) {
377             this.listenerScheduledRestartTime = System.currentTimeMillis() + this.listenerResetLimitInMillsec;
378         } else if (System.currentTimeMillis() > this.listenerScheduledRestartTime
379             && ++this.listenerScheduledRestartEnforceCounter < this.listenerResetEnforceCounter) {
380             // if the transaction failure happens again, we will delay the listener restart up to #LISTENER_RESET_LIMIT_IN_MILLSEC times
381             this.listenerScheduledRestartTime += this.listenerResetLimitInMillsec;
382         }
383         LOG.debug("A listener restart was scheduled at {} (current system time is {})", this.listenerScheduledRestartTime, System.currentTimeMillis());
384     }
385
386     @Override
387     public final synchronized void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
388         LOG.error("Topology builder for {} failed in transaction {}.", getInstanceIdentifier(), transaction != null ? transaction.getIdentifier() : null, cause);
389         scheduleListenerRestart();
390         restartTransactionChainOnDemand();
391     }
392
393     @Override
394     public final void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
395         LOG.info("Topology builder for {} shut down", getInstanceIdentifier());
396     }
397 }