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.OnComplete;
12 import com.google.common.base.Preconditions;
13 import java.util.Collection;
14 import java.util.concurrent.atomic.AtomicInteger;
15 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
16 import org.opendaylight.controller.cluster.datastore.identifiers.TransactionIdentifier;
17 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
18 import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
19 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainClosedException;
20 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
21 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
22 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
23 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27 import scala.concurrent.Future;
28 import scala.concurrent.Promise;
31 * A chain of {@link TransactionProxy}s. It allows a single open transaction to be open
32 * at a time. For remote transactions, it also tracks the outstanding readiness requests
33 * towards the shard and unblocks operations only after all have completed.
35 final class TransactionChainProxy extends AbstractTransactionContextFactory<LocalTransactionChain> implements DOMStoreTransactionChain {
36 private static abstract class State {
38 * Check if it is okay to allocate a new transaction.
39 * @throws IllegalStateException if a transaction may not be allocated.
41 abstract void checkReady();
44 * Return the future which needs to be waited for before shard information
45 * is returned (which unblocks remote transactions).
46 * @return Future to wait for, or null of no wait is necessary
48 abstract Future<?> previousFuture();
51 private static abstract class Pending extends State {
52 private final TransactionIdentifier transaction;
53 private final Future<?> previousFuture;
55 Pending(final TransactionIdentifier transaction, final Future<?> previousFuture) {
56 this.previousFuture = previousFuture;
57 this.transaction = Preconditions.checkNotNull(transaction);
61 final Future<?> previousFuture() {
62 return previousFuture;
65 final TransactionIdentifier getIdentifier() {
70 private static final class Allocated extends Pending {
71 Allocated(final TransactionIdentifier transaction, final Future<?> previousFuture) {
72 super(transaction, previousFuture);
77 throw new IllegalStateException(String.format("Previous transaction %s is not ready yet", getIdentifier()));
81 private static final class Submitted extends Pending {
82 Submitted(final TransactionIdentifier transaction, final Future<?> previousFuture) {
83 super(transaction, previousFuture);
92 private static abstract class DefaultState extends State {
94 final Future<?> previousFuture() {
99 private static final State IDLE_STATE = new DefaultState() {
106 private static final State CLOSED_STATE = new DefaultState() {
109 throw new TransactionChainClosedException("Transaction chain has been closed");
113 private static final Logger LOG = LoggerFactory.getLogger(TransactionChainProxy.class);
114 private static final AtomicInteger CHAIN_COUNTER = new AtomicInteger();
115 private static final AtomicReferenceFieldUpdater<TransactionChainProxy, State> STATE_UPDATER =
116 AtomicReferenceFieldUpdater.newUpdater(TransactionChainProxy.class, State.class, "currentState");
118 private final String transactionChainId;
119 private final TransactionContextFactory parent;
120 private volatile State currentState = IDLE_STATE;
122 TransactionChainProxy(final TransactionContextFactory parent) {
123 super(parent.getActorContext());
124 transactionChainId = parent.getActorContext().getCurrentMemberName() + "-txn-chain-" + CHAIN_COUNTER.incrementAndGet();
125 this.parent = parent;
128 public String getTransactionChainId() {
129 return transactionChainId;
133 public DOMStoreReadTransaction newReadOnlyTransaction() {
134 currentState.checkReady();
135 return new TransactionProxy(this, TransactionType.READ_ONLY);
139 public DOMStoreReadWriteTransaction newReadWriteTransaction() {
140 getActorContext().acquireTxCreationPermit();
141 return allocateWriteTransaction(TransactionType.READ_WRITE);
145 public DOMStoreWriteTransaction newWriteOnlyTransaction() {
146 getActorContext().acquireTxCreationPermit();
147 return allocateWriteTransaction(TransactionType.WRITE_ONLY);
151 public void close() {
152 currentState = CLOSED_STATE;
154 // Send a close transaction chain request to each and every shard
155 getActorContext().broadcast(new CloseTransactionChain(transactionChainId).toSerializable());
156 parent.removeTransactionChain(this);
159 private TransactionProxy allocateWriteTransaction(final TransactionType type) {
160 State localState = currentState;
161 localState.checkReady();
163 final TransactionProxy ret = new TransactionProxy(this, type);
164 currentState = new Allocated(ret.getIdentifier(), localState.previousFuture());
169 protected LocalTransactionChain factoryForShard(final String shardName, final ActorSelection shardLeader, final DataTree dataTree) {
170 final LocalTransactionChain ret = new LocalTransactionChain(this, shardLeader, dataTree);
171 LOG.debug("Allocated transaction chain {} for shard {} leader {}", ret, shardName, shardLeader);
176 protected DataTree dataTreeForFactory(final LocalTransactionChain factory) {
177 return factory.getDataTree();
181 * This method is overridden to ensure the previous Tx's ready operations complete
182 * before we initiate the next Tx in the chain to avoid creation failures if the
183 * previous Tx's ready operations haven't completed yet.
186 protected Future<PrimaryShardInfo> findPrimaryShard(final String shardName) {
187 // Read current state atomically
188 final State localState = currentState;
190 // There are no outstanding futures, shortcut
191 final Future<?> previous = localState.previousFuture();
192 if (previous == null) {
193 return parent.findPrimaryShard(shardName);
196 LOG.debug("Waiting for ready futures for on chain {}", getTransactionChainId());
198 // Add a callback for completion of the combined Futures.
199 final Promise<PrimaryShardInfo> returnPromise = akka.dispatch.Futures.promise();
201 final OnComplete onComplete = new OnComplete() {
203 public void onComplete(final Throwable failure, final Object notUsed) {
204 if (failure != null) {
205 // A Ready Future failed so fail the returned Promise.
206 returnPromise.failure(failure);
208 LOG.debug("Previous Tx readied - proceeding to FindPrimaryShard on chain {}",
209 getTransactionChainId());
211 // Send the FindPrimaryShard message and use the resulting Future to complete the
213 returnPromise.completeWith(parent.findPrimaryShard(shardName));
218 previous.onComplete(onComplete, getActorContext().getClientDispatcher());
219 return returnPromise.future();
223 protected <T> void onTransactionReady(final TransactionIdentifier transaction, final Collection<Future<T>> cohortFutures) {
224 final State localState = currentState;
225 Preconditions.checkState(localState instanceof Allocated, "Readying transaction %s while state is %s", transaction, localState);
226 final TransactionIdentifier currentTx = ((Allocated)localState).getIdentifier();
227 Preconditions.checkState(transaction.equals(currentTx), "Readying transaction %s while %s is allocated", transaction, currentTx);
229 // Transaction ready and we are not waiting for futures -- go to idle
230 if (cohortFutures.isEmpty()) {
231 currentState = IDLE_STATE;
235 // Combine the ready Futures into 1
236 final Future<Iterable<T>> combined = akka.dispatch.Futures.sequence(
237 cohortFutures, getActorContext().getClientDispatcher());
239 // Record the we have outstanding futures
240 final State newState = new Submitted(transaction, combined);
241 currentState = newState;
243 // Attach a completion reset, but only if we do not allocate a transaction
245 combined.onComplete(new OnComplete<Iterable<T>>() {
247 public void onComplete(final Throwable arg0, final Iterable<T> arg1) {
248 STATE_UPDATER.compareAndSet(TransactionChainProxy.this, newState, IDLE_STATE);
250 }, getActorContext().getClientDispatcher());
254 protected TransactionIdentifier nextIdentifier() {
255 return TransactionIdentifier.create(getMemberName(), TX_COUNTER.getAndIncrement(), transactionChainId);