BUG-8665: fix memory leak around RangeSets
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / TransactionChainProxy.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.controller.cluster.datastore;
9
10 import akka.actor.ActorSelection;
11 import akka.dispatch.Futures;
12 import akka.dispatch.OnComplete;
13 import com.google.common.base.Preconditions;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.List;
17 import java.util.Map.Entry;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.ConcurrentMap;
20 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
21 import javax.annotation.Nonnull;
22 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
23 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
24 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
25 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
26 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainClosedException;
27 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
28 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
29 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
30 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
31 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import scala.concurrent.Future;
35 import scala.concurrent.Promise;
36
37 /**
38  * A chain of {@link TransactionProxy}s. It allows a single open transaction to be open
39  * at a time. For remote transactions, it also tracks the outstanding readiness requests
40  * towards the shard and unblocks operations only after all have completed.
41  */
42 final class TransactionChainProxy extends AbstractTransactionContextFactory<LocalTransactionChain>
43         implements DOMStoreTransactionChain {
44     private abstract static class State {
45         /**
46          * Check if it is okay to allocate a new transaction.
47          * @throws IllegalStateException if a transaction may not be allocated.
48          */
49         abstract void checkReady();
50
51         /**
52          * Return the future which needs to be waited for before shard information
53          * is returned (which unblocks remote transactions).
54          * @return Future to wait for, or null of no wait is necessary
55          */
56         abstract Future<?> previousFuture();
57     }
58
59     private abstract static class Pending extends State {
60         private final TransactionIdentifier transaction;
61         private final Future<?> previousFuture;
62
63         Pending(final TransactionIdentifier transaction, final Future<?> previousFuture) {
64             this.previousFuture = previousFuture;
65             this.transaction = Preconditions.checkNotNull(transaction);
66         }
67
68         @Override
69         final Future<?> previousFuture() {
70             return previousFuture;
71         }
72
73         final TransactionIdentifier getIdentifier() {
74             return transaction;
75         }
76     }
77
78     private static final class Allocated extends Pending {
79         Allocated(final TransactionIdentifier transaction, final Future<?> previousFuture) {
80             super(transaction, previousFuture);
81         }
82
83         @Override
84         void checkReady() {
85             throw new IllegalStateException(String.format("Previous transaction %s is not ready yet", getIdentifier()));
86         }
87     }
88
89     private static final class Submitted extends Pending {
90         Submitted(final TransactionIdentifier transaction, final Future<?> previousFuture) {
91             super(transaction, previousFuture);
92         }
93
94         @Override
95         void checkReady() {
96             // Okay to allocate
97         }
98     }
99
100     private abstract static class DefaultState extends State {
101         @Override
102         final Future<?> previousFuture() {
103             return null;
104         }
105     }
106
107     private static final State IDLE_STATE = new DefaultState() {
108         @Override
109         void checkReady() {
110             // Okay to allocate
111         }
112     };
113
114     private static final State CLOSED_STATE = new DefaultState() {
115         @Override
116         void checkReady() {
117             throw new TransactionChainClosedException("Transaction chain has been closed");
118         }
119     };
120
121     private static final Logger LOG = LoggerFactory.getLogger(TransactionChainProxy.class);
122     private static final AtomicReferenceFieldUpdater<TransactionChainProxy, State> STATE_UPDATER =
123             AtomicReferenceFieldUpdater.newUpdater(TransactionChainProxy.class, State.class, "currentState");
124
125     private final TransactionContextFactory parent;
126     private volatile State currentState = IDLE_STATE;
127
128     /**
129      * This map holds Promise instances for each read-only tx. It is used to maintain ordering of tx creates
130      * wrt to read-only tx's between this class and a LocalTransactionChain since they're bridged by
131      * asynchronous futures. Otherwise, in the following scenario, eg:
132      * <p/>
133      *   1) Create write tx1 on chain
134      *   2) do write and submit
135      *   3) Create read-only tx2 on chain and issue read
136      *   4) Create write tx3 on chain, do write but do not submit
137      * <p/>
138      * if the sequence/timing is right, tx3 may create its local tx on the LocalTransactionChain before tx2,
139      * which results in tx2 failing b/c tx3 isn't ready yet. So maintaining ordering prevents this issue
140      * (see Bug 4774).
141      * <p/>
142      * A Promise is added via newReadOnlyTransaction. When the parent class completes the primary shard
143      * lookup and creates the TransactionContext (either success or failure), onTransactionContextCreated is
144      * called which completes the Promise. A write tx that is created prior to completion will wait on the
145      * Promise's Future via findPrimaryShard.
146      */
147     private final ConcurrentMap<TransactionIdentifier, Promise<Object>> priorReadOnlyTxPromises =
148             new ConcurrentHashMap<>();
149
150     TransactionChainProxy(final TransactionContextFactory parent, final LocalHistoryIdentifier historyId) {
151         super(parent.getActorContext(), historyId);
152         this.parent = parent;
153     }
154
155     @Override
156     public DOMStoreReadTransaction newReadOnlyTransaction() {
157         currentState.checkReady();
158         TransactionProxy transactionProxy = new TransactionProxy(this, TransactionType.READ_ONLY);
159         priorReadOnlyTxPromises.put(transactionProxy.getIdentifier(), Futures.<Object>promise());
160         return transactionProxy;
161     }
162
163     @Override
164     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
165         getActorContext().acquireTxCreationPermit();
166         return allocateWriteTransaction(TransactionType.READ_WRITE);
167     }
168
169     @Override
170     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
171         getActorContext().acquireTxCreationPermit();
172         return allocateWriteTransaction(TransactionType.WRITE_ONLY);
173     }
174
175     @Override
176     public void close() {
177         currentState = CLOSED_STATE;
178
179         // Send a close transaction chain request to each and every shard
180
181         getActorContext().broadcast(version -> new CloseTransactionChain(getHistoryId(), version).toSerializable(),
182                 CloseTransactionChain.class);
183     }
184
185     private TransactionProxy allocateWriteTransaction(final TransactionType type) {
186         State localState = currentState;
187         localState.checkReady();
188
189         final TransactionProxy ret = new TransactionProxy(this, type);
190         currentState = new Allocated(ret.getIdentifier(), localState.previousFuture());
191         return ret;
192     }
193
194     @Override
195     protected LocalTransactionChain factoryForShard(final String shardName, final ActorSelection shardLeader,
196             final DataTree dataTree) {
197         final LocalTransactionChain ret = new LocalTransactionChain(this, shardLeader, dataTree);
198         LOG.debug("Allocated transaction chain {} for shard {} leader {}", ret, shardName, shardLeader);
199         return ret;
200     }
201
202     /**
203      * This method is overridden to ensure the previous Tx's ready operations complete
204      * before we initiate the next Tx in the chain to avoid creation failures if the
205      * previous Tx's ready operations haven't completed yet.
206      */
207     @SuppressWarnings({ "unchecked", "rawtypes" })
208     @Override
209     protected Future<PrimaryShardInfo> findPrimaryShard(final String shardName, final TransactionIdentifier txId) {
210         // Read current state atomically
211         final State localState = currentState;
212
213         // There are no outstanding futures, shortcut
214         Future<?> previous = localState.previousFuture();
215         if (previous == null) {
216             return combineFutureWithPossiblePriorReadOnlyTxFutures(parent.findPrimaryShard(shardName, txId), txId);
217         }
218
219         final String previousTransactionId;
220
221         if (localState instanceof Pending) {
222             previousTransactionId = ((Pending) localState).getIdentifier().toString();
223             LOG.debug("Tx: {} - waiting for ready futures with pending Tx {}", txId, previousTransactionId);
224         } else {
225             previousTransactionId = "";
226             LOG.debug("Waiting for ready futures on chain {}", getHistoryId());
227         }
228
229         previous = combineFutureWithPossiblePriorReadOnlyTxFutures(previous, txId);
230
231         // Add a callback for completion of the combined Futures.
232         final Promise<PrimaryShardInfo> returnPromise = Futures.promise();
233
234         final OnComplete onComplete = new OnComplete() {
235             @Override
236             public void onComplete(final Throwable failure, final Object notUsed) {
237                 if (failure != null) {
238                     // A Ready Future failed so fail the returned Promise.
239                     LOG.error("Tx: {} - ready future failed for previous Tx {}", txId, previousTransactionId);
240                     returnPromise.failure(failure);
241                 } else {
242                     LOG.debug("Tx: {} - previous Tx {} readied - proceeding to FindPrimaryShard",
243                             txId, previousTransactionId);
244
245                     // Send the FindPrimaryShard message and use the resulting Future to complete the
246                     // returned Promise.
247                     returnPromise.completeWith(parent.findPrimaryShard(shardName, txId));
248                 }
249             }
250         };
251
252         previous.onComplete(onComplete, getActorContext().getClientDispatcher());
253         return returnPromise.future();
254     }
255
256     private <T> Future<T> combineFutureWithPossiblePriorReadOnlyTxFutures(final Future<T> future,
257             final TransactionIdentifier txId) {
258         if (!priorReadOnlyTxPromises.containsKey(txId) && !priorReadOnlyTxPromises.isEmpty()) {
259             Collection<Entry<TransactionIdentifier, Promise<Object>>> priorReadOnlyTxPromiseEntries =
260                     new ArrayList<>(priorReadOnlyTxPromises.entrySet());
261             if (priorReadOnlyTxPromiseEntries.isEmpty()) {
262                 return future;
263             }
264
265             List<Future<Object>> priorReadOnlyTxFutures = new ArrayList<>(priorReadOnlyTxPromiseEntries.size());
266             for (Entry<TransactionIdentifier, Promise<Object>> entry: priorReadOnlyTxPromiseEntries) {
267                 LOG.debug("Tx: {} - waiting on future for prior read-only Tx {}", txId, entry.getKey());
268                 priorReadOnlyTxFutures.add(entry.getValue().future());
269             }
270
271             Future<Iterable<Object>> combinedFutures = Futures.sequence(priorReadOnlyTxFutures,
272                     getActorContext().getClientDispatcher());
273
274             final Promise<T> returnPromise = Futures.promise();
275             final OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
276                 @Override
277                 public void onComplete(final Throwable failure, final Iterable<Object> notUsed) {
278                     LOG.debug("Tx: {} - prior read-only Tx futures complete", txId);
279
280                     // Complete the returned Promise with the original Future.
281                     returnPromise.completeWith(future);
282                 }
283             };
284
285             combinedFutures.onComplete(onComplete, getActorContext().getClientDispatcher());
286             return returnPromise.future();
287         } else {
288             return future;
289         }
290     }
291
292     @Override
293     protected <T> void onTransactionReady(final TransactionIdentifier transaction,
294             final Collection<Future<T>> cohortFutures) {
295         final State localState = currentState;
296         Preconditions.checkState(localState instanceof Allocated, "Readying transaction %s while state is %s",
297                 transaction, localState);
298         final TransactionIdentifier currentTx = ((Allocated)localState).getIdentifier();
299         Preconditions.checkState(transaction.equals(currentTx), "Readying transaction %s while %s is allocated",
300                 transaction, currentTx);
301
302         // Transaction ready and we are not waiting for futures -- go to idle
303         if (cohortFutures.isEmpty()) {
304             currentState = IDLE_STATE;
305             return;
306         }
307
308         // Combine the ready Futures into 1
309         final Future<Iterable<T>> combined = Futures.sequence(cohortFutures, getActorContext().getClientDispatcher());
310
311         // Record the we have outstanding futures
312         final State newState = new Submitted(transaction, combined);
313         currentState = newState;
314
315         // Attach a completion reset, but only if we do not allocate a transaction
316         // in-between
317         combined.onComplete(new OnComplete<Iterable<T>>() {
318             @Override
319             public void onComplete(final Throwable arg0, final Iterable<T> arg1) {
320                 STATE_UPDATER.compareAndSet(TransactionChainProxy.this, newState, IDLE_STATE);
321             }
322         }, getActorContext().getClientDispatcher());
323     }
324
325     @Override
326     protected void onTransactionContextCreated(@Nonnull TransactionIdentifier transactionId) {
327         Promise<Object> promise = priorReadOnlyTxPromises.remove(transactionId);
328         if (promise != null) {
329             promise.success(null);
330         }
331     }
332 }