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