Bug 4774: Wait for prior RO tx creates on tx chain
[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.AtomicInteger;
21 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
22 import javax.annotation.Nonnull;
23 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionChainIdentifier;
24 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
25 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
26 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
27 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainClosedException;
28 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
29 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
30 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
31 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
32 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import scala.concurrent.Future;
36 import scala.concurrent.Promise;
37
38 /**
39  * A chain of {@link TransactionProxy}s. It allows a single open transaction to be open
40  * at a time. For remote transactions, it also tracks the outstanding readiness requests
41  * towards the shard and unblocks operations only after all have completed.
42  */
43 final class TransactionChainProxy extends AbstractTransactionContextFactory<LocalTransactionChain> implements DOMStoreTransactionChain {
44     private static abstract 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 static abstract 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 static abstract 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 AtomicInteger CHAIN_COUNTER = new AtomicInteger();
123     private static final AtomicReferenceFieldUpdater<TransactionChainProxy, State> STATE_UPDATER =
124             AtomicReferenceFieldUpdater.newUpdater(TransactionChainProxy.class, State.class, "currentState");
125
126     private final TransactionChainIdentifier transactionChainId;
127     private final TransactionContextFactory parent;
128     private volatile State currentState = IDLE_STATE;
129
130     /**
131      * This map holds Promise instances for each read-only tx. It is used to maintain ordering of tx creates
132      * wrt to read-only tx's between this class and a LocalTransactionChain since they're bridged by
133      * asynchronous futures. Otherwise, in the following scenario, eg:
134      *
135      *   1) Create write tx1 on chain
136      *   2) do write and submit
137      *   3) Create read-only tx2 on chain and issue read
138      *   4) Create write tx3 on chain, do write but do not submit
139      *
140      * if the sequence/timing is right, tx3 may create its local tx on the LocalTransactionChain before tx2,
141      * which results in tx2 failing b/c tx3 isn't ready yet. So maintaining ordering prevents this issue
142      * (see Bug 4774).
143      * <p>
144      * A Promise is added via newReadOnlyTransaction. When the parent class completes the primary shard
145      * lookup and creates the TransactionContext (either success or failure), onTransactionContextCreated is
146      * called which completes the Promise. A write tx that is created prior to completion will wait on the
147      * Promise's Future via findPrimaryShard.
148      */
149     private final ConcurrentMap<TransactionIdentifier, Promise<Object>> priorReadOnlyTxPromises = new ConcurrentHashMap<>();
150
151     TransactionChainProxy(final TransactionContextFactory parent) {
152         super(parent.getActorContext());
153
154         transactionChainId = new TransactionChainIdentifier(parent.getActorContext().getCurrentMemberName(), CHAIN_COUNTER.incrementAndGet());
155         this.parent = parent;
156     }
157
158     public String getTransactionChainId() {
159         return transactionChainId.toString();
160     }
161
162     @Override
163     public DOMStoreReadTransaction newReadOnlyTransaction() {
164         currentState.checkReady();
165         TransactionProxy transactionProxy = new TransactionProxy(this, TransactionType.READ_ONLY);
166         priorReadOnlyTxPromises.put(transactionProxy.getIdentifier(), Futures.<Object>promise());
167         return transactionProxy;
168     }
169
170     @Override
171     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
172         getActorContext().acquireTxCreationPermit();
173         return allocateWriteTransaction(TransactionType.READ_WRITE);
174     }
175
176     @Override
177     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
178         getActorContext().acquireTxCreationPermit();
179         return allocateWriteTransaction(TransactionType.WRITE_ONLY);
180     }
181
182     @Override
183     public void close() {
184         currentState = CLOSED_STATE;
185
186         // Send a close transaction chain request to each and every shard
187         getActorContext().broadcast(new CloseTransactionChain(transactionChainId.toString()).toSerializable());
188     }
189
190     private TransactionProxy allocateWriteTransaction(final TransactionType type) {
191         State localState = currentState;
192         localState.checkReady();
193
194         final TransactionProxy ret = new TransactionProxy(this, type);
195         currentState = new Allocated(ret.getIdentifier(), localState.previousFuture());
196         return ret;
197     }
198
199     @Override
200     protected LocalTransactionChain factoryForShard(final String shardName, final ActorSelection shardLeader, final DataTree dataTree) {
201         final LocalTransactionChain ret = new LocalTransactionChain(this, shardLeader, dataTree);
202         LOG.debug("Allocated transaction chain {} for shard {} leader {}", ret, shardName, shardLeader);
203         return ret;
204     }
205
206     /**
207      * This method is overridden to ensure the previous Tx's ready operations complete
208      * before we initiate the next Tx in the chain to avoid creation failures if the
209      * previous Tx's ready operations haven't completed yet.
210      */
211     @SuppressWarnings({ "unchecked", "rawtypes" })
212     @Override
213     protected Future<PrimaryShardInfo> findPrimaryShard(final String shardName, final TransactionIdentifier txId) {
214         // Read current state atomically
215         final State localState = currentState;
216
217         // There are no outstanding futures, shortcut
218         Future<?> previous = localState.previousFuture();
219         if (previous == null) {
220             return combineFutureWithPossiblePriorReadOnlyTxFutures(parent.findPrimaryShard(shardName, txId), txId);
221         }
222
223         final String previousTransactionId;
224
225         if(localState instanceof Pending){
226             previousTransactionId = ((Pending) localState).getIdentifier().toString();
227             LOG.debug("Tx: {} - waiting for ready futures with pending Tx {}", txId, previousTransactionId);
228         } else {
229             previousTransactionId = "";
230             LOG.debug("Waiting for ready futures on chain {}", getTransactionChainId());
231         }
232
233         previous = combineFutureWithPossiblePriorReadOnlyTxFutures(previous, txId);
234
235         // Add a callback for completion of the combined Futures.
236         final Promise<PrimaryShardInfo> returnPromise = Futures.promise();
237
238         final OnComplete onComplete = new OnComplete() {
239             @Override
240             public void onComplete(final Throwable failure, final Object notUsed) {
241                 if (failure != null) {
242                     // A Ready Future failed so fail the returned Promise.
243                     LOG.error("Tx: {} - ready future failed for previous Tx {}", txId, previousTransactionId);
244                     returnPromise.failure(failure);
245                 } else {
246                     LOG.debug("Tx: {} - previous Tx {} readied - proceeding to FindPrimaryShard",
247                             txId, previousTransactionId);
248
249                     // Send the FindPrimaryShard message and use the resulting Future to complete the
250                     // returned Promise.
251                     returnPromise.completeWith(parent.findPrimaryShard(shardName, txId));
252                 }
253             }
254         };
255
256         previous.onComplete(onComplete, getActorContext().getClientDispatcher());
257         return returnPromise.future();
258     }
259
260     private <T> Future<T> combineFutureWithPossiblePriorReadOnlyTxFutures(final Future<T> future,
261             final TransactionIdentifier txId) {
262         if(!priorReadOnlyTxPromises.containsKey(txId) && !priorReadOnlyTxPromises.isEmpty()) {
263             Collection<Entry<TransactionIdentifier, Promise<Object>>> priorReadOnlyTxPromiseEntries =
264                     new ArrayList<>(priorReadOnlyTxPromises.entrySet());
265             if(priorReadOnlyTxPromiseEntries.isEmpty()) {
266                 return future;
267             }
268
269             List<Future<Object>> priorReadOnlyTxFutures = new ArrayList<>(priorReadOnlyTxPromiseEntries.size());
270             for(Entry<TransactionIdentifier, Promise<Object>> entry: priorReadOnlyTxPromiseEntries) {
271                 LOG.debug("Tx: {} - waiting on future for prior read-only Tx {}", txId, entry.getKey());
272                 priorReadOnlyTxFutures.add(entry.getValue().future());
273             }
274
275             Future<Iterable<Object>> combinedFutures = Futures.sequence(priorReadOnlyTxFutures,
276                     getActorContext().getClientDispatcher());
277
278             final Promise<T> returnPromise = Futures.promise();
279             final OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
280                 @Override
281                 public void onComplete(final Throwable failure, final Iterable<Object> notUsed) {
282                     LOG.debug("Tx: {} - prior read-only Tx futures complete", txId);
283
284                     // Complete the returned Promise with the original Future.
285                     returnPromise.completeWith(future);
286                 }
287             };
288
289             combinedFutures.onComplete(onComplete, getActorContext().getClientDispatcher());
290             return returnPromise.future();
291         } else {
292             return future;
293         }
294     }
295
296     @Override
297     protected <T> void onTransactionReady(final TransactionIdentifier transaction, final Collection<Future<T>> cohortFutures) {
298         final State localState = currentState;
299         Preconditions.checkState(localState instanceof Allocated, "Readying transaction %s while state is %s", transaction, localState);
300         final TransactionIdentifier currentTx = ((Allocated)localState).getIdentifier();
301         Preconditions.checkState(transaction.equals(currentTx), "Readying transaction %s while %s is allocated", transaction, currentTx);
302
303         // Transaction ready and we are not waiting for futures -- go to idle
304         if (cohortFutures.isEmpty()) {
305             currentState = IDLE_STATE;
306             return;
307         }
308
309         // Combine the ready Futures into 1
310         final Future<Iterable<T>> combined = Futures.sequence(cohortFutures, getActorContext().getClientDispatcher());
311
312         // Record the we have outstanding futures
313         final State newState = new Submitted(transaction, combined);
314         currentState = newState;
315
316         // Attach a completion reset, but only if we do not allocate a transaction
317         // in-between
318         combined.onComplete(new OnComplete<Iterable<T>>() {
319             @Override
320             public void onComplete(final Throwable arg0, final Iterable<T> arg1) {
321                 STATE_UPDATER.compareAndSet(TransactionChainProxy.this, newState, IDLE_STATE);
322             }
323         }, getActorContext().getClientDispatcher());
324     }
325
326     @Override
327     protected void onTransactionContextCreated(@Nonnull TransactionIdentifier transactionId) {
328         Promise<Object> promise = priorReadOnlyTxPromises.remove(transactionId);
329         if(promise != null) {
330             promise.success(null);
331         }
332     }
333
334     @Override
335     protected TransactionIdentifier nextIdentifier() {
336         return transactionChainId.newTransactionIdentifier();
337     }
338 }