2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.datastore;
10 import static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
13 import akka.actor.ActorSelection;
14 import akka.dispatch.Futures;
15 import akka.dispatch.OnComplete;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.List;
19 import java.util.Map.Entry;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ConcurrentMap;
22 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
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.mdsal.dom.api.DOMTransactionChainClosedException;
28 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
29 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
30 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
31 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
32 import org.opendaylight.yangtools.yang.data.api.schema.tree.ReadOnlyDataTree;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import scala.concurrent.Future;
36 import scala.concurrent.Promise;
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.
43 final class TransactionChainProxy extends AbstractTransactionContextFactory<LocalTransactionChain>
44 implements DOMStoreTransactionChain {
45 private abstract static class State {
47 * Check if it is okay to allocate a new transaction.
48 * @throws IllegalStateException if a transaction may not be allocated.
50 abstract void checkReady();
53 * Return the future which needs to be waited for before shard information
54 * is returned (which unblocks remote transactions).
55 * @return Future to wait for, or null of no wait is necessary
57 abstract Future<?> previousFuture();
60 private abstract static class Pending extends State {
61 private final TransactionIdentifier transaction;
62 private final Future<?> previousFuture;
64 Pending(final TransactionIdentifier transaction, final Future<?> previousFuture) {
65 this.previousFuture = previousFuture;
66 this.transaction = requireNonNull(transaction);
70 final Future<?> previousFuture() {
71 return previousFuture;
74 final TransactionIdentifier getIdentifier() {
79 private static final class Allocated extends Pending {
80 Allocated(final TransactionIdentifier transaction, final Future<?> previousFuture) {
81 super(transaction, previousFuture);
86 throw new IllegalStateException(String.format("Previous transaction %s is not ready yet", getIdentifier()));
90 private static final class Submitted extends Pending {
91 Submitted(final TransactionIdentifier transaction, final Future<?> previousFuture) {
92 super(transaction, previousFuture);
101 private abstract static class DefaultState extends State {
103 final Future<?> previousFuture() {
108 private static final State IDLE_STATE = new DefaultState() {
115 private static final State CLOSED_STATE = new DefaultState() {
118 throw new DOMTransactionChainClosedException("Transaction chain has been closed");
122 private static final Logger LOG = LoggerFactory.getLogger(TransactionChainProxy.class);
123 private static final AtomicReferenceFieldUpdater<TransactionChainProxy, State> STATE_UPDATER =
124 AtomicReferenceFieldUpdater.newUpdater(TransactionChainProxy.class, State.class, "currentState");
126 private final TransactionContextFactory parent;
127 private volatile State currentState = IDLE_STATE;
130 * This map holds Promise instances for each read-only tx. It is used to maintain ordering of tx creates
131 * wrt to read-only tx's between this class and a LocalTransactionChain since they're bridged by
132 * asynchronous futures. Otherwise, in the following scenario, eg:
134 * 1) Create write tx1 on chain
135 * 2) do write and submit
136 * 3) Create read-only tx2 on chain and issue read
137 * 4) Create write tx3 on chain, do write but do not submit
139 * if the sequence/timing is right, tx3 may create its local tx on the LocalTransactionChain before tx2,
140 * which results in tx2 failing b/c tx3 isn't ready yet. So maintaining ordering prevents this issue
143 * A Promise is added via newReadOnlyTransaction. When the parent class completes the primary shard
144 * lookup and creates the TransactionContext (either success or failure), onTransactionContextCreated is
145 * called which completes the Promise. A write tx that is created prior to completion will wait on the
146 * Promise's Future via findPrimaryShard.
148 private final ConcurrentMap<TransactionIdentifier, Promise<Object>> priorReadOnlyTxPromises =
149 new ConcurrentHashMap<>();
151 TransactionChainProxy(final TransactionContextFactory parent, final LocalHistoryIdentifier historyId) {
152 super(parent.getActorUtils(), historyId);
153 this.parent = parent;
157 public DOMStoreReadTransaction newReadOnlyTransaction() {
158 currentState.checkReady();
159 TransactionProxy transactionProxy = new TransactionProxy(this, TransactionType.READ_ONLY);
160 priorReadOnlyTxPromises.put(transactionProxy.getIdentifier(), Futures.<Object>promise());
161 return transactionProxy;
165 public DOMStoreReadWriteTransaction newReadWriteTransaction() {
166 getActorUtils().acquireTxCreationPermit();
167 return allocateWriteTransaction(TransactionType.READ_WRITE);
171 public DOMStoreWriteTransaction newWriteOnlyTransaction() {
172 getActorUtils().acquireTxCreationPermit();
173 return allocateWriteTransaction(TransactionType.WRITE_ONLY);
177 public void close() {
178 currentState = CLOSED_STATE;
180 // Send a close transaction chain request to each and every shard
182 getActorUtils().broadcast(version -> new CloseTransactionChain(getHistoryId(), version).toSerializable(),
183 CloseTransactionChain.class);
186 private TransactionProxy allocateWriteTransaction(final TransactionType type) {
187 State localState = currentState;
188 localState.checkReady();
190 final TransactionProxy ret = new TransactionProxy(this, type);
191 currentState = new Allocated(ret.getIdentifier(), localState.previousFuture());
196 protected LocalTransactionChain factoryForShard(final String shardName, final ActorSelection shardLeader,
197 final ReadOnlyDataTree dataTree) {
198 final LocalTransactionChain ret = new LocalTransactionChain(this, shardLeader, dataTree);
199 LOG.debug("Allocated transaction chain {} for shard {} leader {}", ret, shardName, shardLeader);
204 * This method is overridden to ensure the previous Tx's ready operations complete
205 * before we initiate the next Tx in the chain to avoid creation failures if the
206 * previous Tx's ready operations haven't completed yet.
208 @SuppressWarnings({ "unchecked", "rawtypes" })
210 protected Future<PrimaryShardInfo> findPrimaryShard(final String shardName, final TransactionIdentifier txId) {
211 // Read current state atomically
212 final State localState = currentState;
214 // There are no outstanding futures, shortcut
215 Future<?> previous = localState.previousFuture();
216 if (previous == null) {
217 return combineFutureWithPossiblePriorReadOnlyTxFutures(parent.findPrimaryShard(shardName, txId), txId);
220 final String previousTransactionId;
222 if (localState instanceof Pending) {
223 previousTransactionId = ((Pending) localState).getIdentifier().toString();
224 LOG.debug("Tx: {} - waiting for ready futures with pending Tx {}", txId, previousTransactionId);
226 previousTransactionId = "";
227 LOG.debug("Waiting for ready futures on chain {}", getHistoryId());
230 previous = combineFutureWithPossiblePriorReadOnlyTxFutures(previous, txId);
232 // Add a callback for completion of the combined Futures.
233 final Promise<PrimaryShardInfo> returnPromise = Futures.promise();
235 final OnComplete onComplete = new OnComplete() {
237 public void onComplete(final Throwable failure, final Object notUsed) {
238 if (failure != null) {
239 // A Ready Future failed so fail the returned Promise.
240 LOG.error("Tx: {} - ready future failed for previous Tx {}", txId, previousTransactionId);
241 returnPromise.failure(failure);
243 LOG.debug("Tx: {} - previous Tx {} readied - proceeding to FindPrimaryShard",
244 txId, previousTransactionId);
246 // Send the FindPrimaryShard message and use the resulting Future to complete the
248 returnPromise.completeWith(parent.findPrimaryShard(shardName, txId));
253 previous.onComplete(onComplete, getActorUtils().getClientDispatcher());
254 return returnPromise.future();
257 private <T> Future<T> combineFutureWithPossiblePriorReadOnlyTxFutures(final Future<T> future,
258 final TransactionIdentifier txId) {
259 return priorReadOnlyTxPromises.isEmpty() || priorReadOnlyTxPromises.containsKey(txId) ? future
260 // Tough luck, we need do some work
261 : combineWithPriorReadOnlyTxFutures(future, txId);
264 // Split out of the common path
265 private <T> Future<T> combineWithPriorReadOnlyTxFutures(final Future<T> future, final TransactionIdentifier txId) {
266 // Take a stable snapshot, and check if we raced
267 final List<Entry<TransactionIdentifier, Promise<Object>>> priorReadOnlyTxPromiseEntries =
268 new ArrayList<>(priorReadOnlyTxPromises.entrySet());
269 if (priorReadOnlyTxPromiseEntries.isEmpty()) {
273 final List<Future<Object>> priorReadOnlyTxFutures = new ArrayList<>(priorReadOnlyTxPromiseEntries.size());
274 for (Entry<TransactionIdentifier, Promise<Object>> entry: priorReadOnlyTxPromiseEntries) {
275 LOG.debug("Tx: {} - waiting on future for prior read-only Tx {}", txId, entry.getKey());
276 priorReadOnlyTxFutures.add(entry.getValue().future());
279 final Future<Iterable<Object>> combinedFutures = Futures.sequence(priorReadOnlyTxFutures,
280 getActorUtils().getClientDispatcher());
282 final Promise<T> returnPromise = Futures.promise();
283 final OnComplete<Iterable<Object>> onComplete = new OnComplete<>() {
285 public void onComplete(final Throwable failure, final Iterable<Object> notUsed) {
286 LOG.debug("Tx: {} - prior read-only Tx futures complete", txId);
288 // Complete the returned Promise with the original Future.
289 returnPromise.completeWith(future);
293 combinedFutures.onComplete(onComplete, getActorUtils().getClientDispatcher());
294 return returnPromise.future();
298 protected <T> void onTransactionReady(final TransactionIdentifier transaction,
299 final Collection<Future<T>> cohortFutures) {
300 final State localState = currentState;
301 checkState(localState instanceof Allocated, "Readying transaction %s while state is %s", transaction,
303 final TransactionIdentifier currentTx = ((Allocated)localState).getIdentifier();
304 checkState(transaction.equals(currentTx), "Readying transaction %s while %s is allocated", transaction,
307 // Transaction ready and we are not waiting for futures -- go to idle
308 if (cohortFutures.isEmpty()) {
309 currentState = IDLE_STATE;
313 // Combine the ready Futures into 1
314 final Future<Iterable<T>> combined = Futures.sequence(cohortFutures, getActorUtils().getClientDispatcher());
316 // Record the we have outstanding futures
317 final State newState = new Submitted(transaction, combined);
318 currentState = newState;
320 // Attach a completion reset, but only if we do not allocate a transaction
322 combined.onComplete(new OnComplete<Iterable<T>>() {
324 public void onComplete(final Throwable arg0, final Iterable<T> arg1) {
325 STATE_UPDATER.compareAndSet(TransactionChainProxy.this, newState, IDLE_STATE);
327 }, getActorUtils().getClientDispatcher());
331 protected void onTransactionContextCreated(final TransactionIdentifier transactionId) {
332 Promise<Object> promise = priorReadOnlyTxPromises.remove(transactionId);
333 if (promise != null) {
334 promise.success(null);