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 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.mdsal.dom.api.DOMTransactionChainClosedException;
27 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
28 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
29 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
30 import org.opendaylight.mdsal.dom.spi.store.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;
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.
42 final class TransactionChainProxy extends AbstractTransactionContextFactory<LocalTransactionChain>
43 implements DOMStoreTransactionChain {
44 private abstract static class State {
46 * Check if it is okay to allocate a new transaction.
47 * @throws IllegalStateException if a transaction may not be allocated.
49 abstract void checkReady();
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
56 abstract Future<?> previousFuture();
59 private abstract static class Pending extends State {
60 private final TransactionIdentifier transaction;
61 private final Future<?> previousFuture;
63 Pending(final TransactionIdentifier transaction, final Future<?> previousFuture) {
64 this.previousFuture = previousFuture;
65 this.transaction = Preconditions.checkNotNull(transaction);
69 final Future<?> previousFuture() {
70 return previousFuture;
73 final TransactionIdentifier getIdentifier() {
78 private static final class Allocated extends Pending {
79 Allocated(final TransactionIdentifier transaction, final Future<?> previousFuture) {
80 super(transaction, previousFuture);
85 throw new IllegalStateException(String.format("Previous transaction %s is not ready yet", getIdentifier()));
89 private static final class Submitted extends Pending {
90 Submitted(final TransactionIdentifier transaction, final Future<?> previousFuture) {
91 super(transaction, previousFuture);
100 private abstract static class DefaultState extends State {
102 final Future<?> previousFuture() {
107 private static final State IDLE_STATE = new DefaultState() {
114 private static final State CLOSED_STATE = new DefaultState() {
117 throw new DOMTransactionChainClosedException("Transaction chain has been closed");
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");
125 private final TransactionContextFactory parent;
126 private volatile State currentState = IDLE_STATE;
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:
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
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
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.
147 private final ConcurrentMap<TransactionIdentifier, Promise<Object>> priorReadOnlyTxPromises =
148 new ConcurrentHashMap<>();
150 TransactionChainProxy(final TransactionContextFactory parent, final LocalHistoryIdentifier historyId) {
151 super(parent.getActorContext(), historyId);
152 this.parent = parent;
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;
164 public DOMStoreReadWriteTransaction newReadWriteTransaction() {
165 getActorContext().acquireTxCreationPermit();
166 return allocateWriteTransaction(TransactionType.READ_WRITE);
170 public DOMStoreWriteTransaction newWriteOnlyTransaction() {
171 getActorContext().acquireTxCreationPermit();
172 return allocateWriteTransaction(TransactionType.WRITE_ONLY);
176 public void close() {
177 currentState = CLOSED_STATE;
179 // Send a close transaction chain request to each and every shard
181 getActorContext().broadcast(version -> new CloseTransactionChain(getHistoryId(), version).toSerializable(),
182 CloseTransactionChain.class);
185 private TransactionProxy allocateWriteTransaction(final TransactionType type) {
186 State localState = currentState;
187 localState.checkReady();
189 final TransactionProxy ret = new TransactionProxy(this, type);
190 currentState = new Allocated(ret.getIdentifier(), localState.previousFuture());
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);
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.
207 @SuppressWarnings({ "unchecked", "rawtypes" })
209 protected Future<PrimaryShardInfo> findPrimaryShard(final String shardName, final TransactionIdentifier txId) {
210 // Read current state atomically
211 final State localState = currentState;
213 // There are no outstanding futures, shortcut
214 Future<?> previous = localState.previousFuture();
215 if (previous == null) {
216 return combineFutureWithPossiblePriorReadOnlyTxFutures(parent.findPrimaryShard(shardName, txId), txId);
219 final String previousTransactionId;
221 if (localState instanceof Pending) {
222 previousTransactionId = ((Pending) localState).getIdentifier().toString();
223 LOG.debug("Tx: {} - waiting for ready futures with pending Tx {}", txId, previousTransactionId);
225 previousTransactionId = "";
226 LOG.debug("Waiting for ready futures on chain {}", getHistoryId());
229 previous = combineFutureWithPossiblePriorReadOnlyTxFutures(previous, txId);
231 // Add a callback for completion of the combined Futures.
232 final Promise<PrimaryShardInfo> returnPromise = Futures.promise();
234 final OnComplete onComplete = new OnComplete() {
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);
242 LOG.debug("Tx: {} - previous Tx {} readied - proceeding to FindPrimaryShard",
243 txId, previousTransactionId);
245 // Send the FindPrimaryShard message and use the resulting Future to complete the
247 returnPromise.completeWith(parent.findPrimaryShard(shardName, txId));
252 previous.onComplete(onComplete, getActorContext().getClientDispatcher());
253 return returnPromise.future();
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()) {
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());
271 Future<Iterable<Object>> combinedFutures = Futures.sequence(priorReadOnlyTxFutures,
272 getActorContext().getClientDispatcher());
274 final Promise<T> returnPromise = Futures.promise();
275 final OnComplete<Iterable<Object>> onComplete = new OnComplete<Iterable<Object>>() {
277 public void onComplete(final Throwable failure, final Iterable<Object> notUsed) {
278 LOG.debug("Tx: {} - prior read-only Tx futures complete", txId);
280 // Complete the returned Promise with the original Future.
281 returnPromise.completeWith(future);
285 combinedFutures.onComplete(onComplete, getActorContext().getClientDispatcher());
286 return returnPromise.future();
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);
302 // Transaction ready and we are not waiting for futures -- go to idle
303 if (cohortFutures.isEmpty()) {
304 currentState = IDLE_STATE;
308 // Combine the ready Futures into 1
309 final Future<Iterable<T>> combined = Futures.sequence(cohortFutures, getActorContext().getClientDispatcher());
311 // Record the we have outstanding futures
312 final State newState = new Submitted(transaction, combined);
313 currentState = newState;
315 // Attach a completion reset, but only if we do not allocate a transaction
317 combined.onComplete(new OnComplete<Iterable<T>>() {
319 public void onComplete(final Throwable arg0, final Iterable<T> arg1) {
320 STATE_UPDATER.compareAndSet(TransactionChainProxy.this, newState, IDLE_STATE);
322 }, getActorContext().getClientDispatcher());
326 protected void onTransactionContextCreated(@Nonnull TransactionIdentifier transactionId) {
327 Promise<Object> promise = priorReadOnlyTxPromises.remove(transactionId);
328 if (promise != null) {
329 promise.success(null);