BUG-5903: do not rely on primary info on failure
[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 java.util.function.Function;
22 import javax.annotation.Nonnull;
23 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
24 import org.opendaylight.controller.cluster.access.concepts.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 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      *
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      *
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 = new ConcurrentHashMap<>();
148
149     TransactionChainProxy(final TransactionContextFactory parent, final LocalHistoryIdentifier historyId) {
150         super(parent.getActorContext(), historyId);
151         this.parent = parent;
152     }
153
154     @Override
155     public DOMStoreReadTransaction newReadOnlyTransaction() {
156         currentState.checkReady();
157         TransactionProxy transactionProxy = new TransactionProxy(this, TransactionType.READ_ONLY);
158         priorReadOnlyTxPromises.put(transactionProxy.getIdentifier(), Futures.<Object>promise());
159         return transactionProxy;
160     }
161
162     @Override
163     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
164         getActorContext().acquireTxCreationPermit();
165         return allocateWriteTransaction(TransactionType.READ_WRITE);
166     }
167
168     @Override
169     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
170         getActorContext().acquireTxCreationPermit();
171         return allocateWriteTransaction(TransactionType.WRITE_ONLY);
172     }
173
174     @Override
175     public void close() {
176         currentState = CLOSED_STATE;
177
178         // Send a close transaction chain request to each and every shard
179
180         getActorContext().broadcast(new Function<Short, Object>() {
181             @Override
182             public Object apply(Short version) {
183                 return new CloseTransactionChain(getHistoryId(), version).toSerializable();
184             }
185         }, CloseTransactionChain.class);
186     }
187
188     private TransactionProxy allocateWriteTransaction(final TransactionType type) {
189         State localState = currentState;
190         localState.checkReady();
191
192         final TransactionProxy ret = new TransactionProxy(this, type);
193         currentState = new Allocated(ret.getIdentifier(), localState.previousFuture());
194         return ret;
195     }
196
197     @Override
198     protected LocalTransactionChain factoryForShard(final String shardName, final ActorSelection shardLeader, final DataTree dataTree) {
199         final LocalTransactionChain ret = new LocalTransactionChain(this, shardLeader, dataTree);
200         LOG.debug("Allocated transaction chain {} for shard {} leader {}", ret, shardName, shardLeader);
201         return ret;
202     }
203
204     /**
205      * This method is overridden to ensure the previous Tx's ready operations complete
206      * before we initiate the next Tx in the chain to avoid creation failures if the
207      * previous Tx's ready operations haven't completed yet.
208      */
209     @SuppressWarnings({ "unchecked", "rawtypes" })
210     @Override
211     protected Future<PrimaryShardInfo> findPrimaryShard(final String shardName, final TransactionIdentifier txId) {
212         // Read current state atomically
213         final State localState = currentState;
214
215         // There are no outstanding futures, shortcut
216         Future<?> previous = localState.previousFuture();
217         if (previous == null) {
218             return combineFutureWithPossiblePriorReadOnlyTxFutures(parent.findPrimaryShard(shardName, txId), txId);
219         }
220
221         final String previousTransactionId;
222
223         if(localState instanceof Pending){
224             previousTransactionId = ((Pending) localState).getIdentifier().toString();
225             LOG.debug("Tx: {} - waiting for ready futures with pending Tx {}", txId, previousTransactionId);
226         } else {
227             previousTransactionId = "";
228             LOG.debug("Waiting for ready futures on chain {}", getHistoryId());
229         }
230
231         previous = combineFutureWithPossiblePriorReadOnlyTxFutures(previous, txId);
232
233         // Add a callback for completion of the combined Futures.
234         final Promise<PrimaryShardInfo> returnPromise = Futures.promise();
235
236         final OnComplete onComplete = new OnComplete() {
237             @Override
238             public void onComplete(final Throwable failure, final Object notUsed) {
239                 if (failure != null) {
240                     // A Ready Future failed so fail the returned Promise.
241                     LOG.error("Tx: {} - ready future failed for previous Tx {}", txId, previousTransactionId);
242                     returnPromise.failure(failure);
243                 } else {
244                     LOG.debug("Tx: {} - previous Tx {} readied - proceeding to FindPrimaryShard",
245                             txId, previousTransactionId);
246
247                     // Send the FindPrimaryShard message and use the resulting Future to complete the
248                     // returned Promise.
249                     returnPromise.completeWith(parent.findPrimaryShard(shardName, txId));
250                 }
251             }
252         };
253
254         previous.onComplete(onComplete, getActorContext().getClientDispatcher());
255         return returnPromise.future();
256     }
257
258     private <T> Future<T> combineFutureWithPossiblePriorReadOnlyTxFutures(final Future<T> future,
259             final TransactionIdentifier txId) {
260         if(!priorReadOnlyTxPromises.containsKey(txId) && !priorReadOnlyTxPromises.isEmpty()) {
261             Collection<Entry<TransactionIdentifier, Promise<Object>>> priorReadOnlyTxPromiseEntries =
262                     new ArrayList<>(priorReadOnlyTxPromises.entrySet());
263             if(priorReadOnlyTxPromiseEntries.isEmpty()) {
264                 return future;
265             }
266
267             List<Future<Object>> priorReadOnlyTxFutures = new ArrayList<>(priorReadOnlyTxPromiseEntries.size());
268             for(Entry<TransactionIdentifier, Promise<Object>> entry: priorReadOnlyTxPromiseEntries) {
269                 LOG.debug("Tx: {} - waiting on future for prior read-only Tx {}", txId, entry.getKey());
270                 priorReadOnlyTxFutures.add(entry.getValue().future());
271             }
272
273             Future<Iterable<Object>> combinedFutures = Futures.sequence(priorReadOnlyTxFutures,
274                     getActorContext().getClientDispatcher());
275
276             final Promise<T> returnPromise = Futures.promise();
277             final OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
278                 @Override
279                 public void onComplete(final Throwable failure, final Iterable<Object> notUsed) {
280                     LOG.debug("Tx: {} - prior read-only Tx futures complete", txId);
281
282                     // Complete the returned Promise with the original Future.
283                     returnPromise.completeWith(future);
284                 }
285             };
286
287             combinedFutures.onComplete(onComplete, getActorContext().getClientDispatcher());
288             return returnPromise.future();
289         } else {
290             return future;
291         }
292     }
293
294     @Override
295     protected <T> void onTransactionReady(final TransactionIdentifier transaction, final Collection<Future<T>> cohortFutures) {
296         final State localState = currentState;
297         Preconditions.checkState(localState instanceof Allocated, "Readying transaction %s while state is %s", transaction, localState);
298         final TransactionIdentifier currentTx = ((Allocated)localState).getIdentifier();
299         Preconditions.checkState(transaction.equals(currentTx), "Readying transaction %s while %s is allocated", transaction, currentTx);
300
301         // Transaction ready and we are not waiting for futures -- go to idle
302         if (cohortFutures.isEmpty()) {
303             currentState = IDLE_STATE;
304             return;
305         }
306
307         // Combine the ready Futures into 1
308         final Future<Iterable<T>> combined = Futures.sequence(cohortFutures, getActorContext().getClientDispatcher());
309
310         // Record the we have outstanding futures
311         final State newState = new Submitted(transaction, combined);
312         currentState = newState;
313
314         // Attach a completion reset, but only if we do not allocate a transaction
315         // in-between
316         combined.onComplete(new OnComplete<Iterable<T>>() {
317             @Override
318             public void onComplete(final Throwable arg0, final Iterable<T> arg1) {
319                 STATE_UPDATER.compareAndSet(TransactionChainProxy.this, newState, IDLE_STATE);
320             }
321         }, getActorContext().getClientDispatcher());
322     }
323
324     @Override
325     protected void onTransactionContextCreated(@Nonnull TransactionIdentifier transactionId) {
326         Promise<Object> promise = priorReadOnlyTxPromises.remove(transactionId);
327         if(promise != null) {
328             promise.success(null);
329         }
330     }
331 }