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