CDS: Implement front-end support for local transactions
[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.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;
29
30 /**
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.
34  */
35 final class TransactionChainProxy extends AbstractTransactionContextFactory<LocalTransactionChain> implements DOMStoreTransactionChain {
36     private static abstract class State {
37         /**
38          * Check if it is okay to allocate a new transaction.
39          * @throws IllegalStateException if a transaction may not be allocated.
40          */
41         abstract void checkReady();
42
43         /**
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
47          */
48         abstract Future<?> previousFuture();
49     }
50
51     private static abstract class Pending extends State {
52         private final TransactionIdentifier transaction;
53         private final Future<?> previousFuture;
54
55         Pending(final TransactionIdentifier transaction, final Future<?> previousFuture) {
56             this.previousFuture = previousFuture;
57             this.transaction = Preconditions.checkNotNull(transaction);
58         }
59
60         @Override
61         final Future<?> previousFuture() {
62             return previousFuture;
63         }
64
65         final TransactionIdentifier getIdentifier() {
66             return transaction;
67         }
68     }
69
70     private static final class Allocated extends Pending {
71         Allocated(final TransactionIdentifier transaction, final Future<?> previousFuture) {
72             super(transaction, previousFuture);
73         }
74
75         @Override
76         void checkReady() {
77             throw new IllegalStateException(String.format("Previous transaction %s is not ready yet", getIdentifier()));
78         }
79     }
80
81     private static final class Submitted extends Pending {
82         Submitted(final TransactionIdentifier transaction, final Future<?> previousFuture) {
83             super(transaction, previousFuture);
84         }
85
86         @Override
87         void checkReady() {
88             // Okay to allocate
89         }
90     }
91
92     private static abstract class DefaultState extends State {
93         @Override
94         final Future<?> previousFuture() {
95             return null;
96         }
97     }
98
99     private static final State IDLE_STATE = new DefaultState() {
100         @Override
101         void checkReady() {
102             // Okay to allocate
103         }
104     };
105
106     private static final State CLOSED_STATE = new DefaultState() {
107         @Override
108         void checkReady() {
109             throw new TransactionChainClosedException("Transaction chain has been closed");
110         }
111     };
112
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");
117
118     private final String transactionChainId;
119     private final TransactionContextFactory parent;
120     private volatile State currentState = IDLE_STATE;
121
122     TransactionChainProxy(final TransactionContextFactory parent) {
123         super(parent.getActorContext());
124         transactionChainId = parent.getActorContext().getCurrentMemberName() + "-txn-chain-" + CHAIN_COUNTER.incrementAndGet();
125         this.parent = parent;
126     }
127
128     public String getTransactionChainId() {
129         return transactionChainId;
130     }
131
132     @Override
133     public DOMStoreReadTransaction newReadOnlyTransaction() {
134         currentState.checkReady();
135         return new TransactionProxy(this, TransactionType.READ_ONLY);
136     }
137
138     @Override
139     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
140         getActorContext().acquireTxCreationPermit();
141         return allocateWriteTransaction(TransactionType.READ_WRITE);
142     }
143
144     @Override
145     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
146         getActorContext().acquireTxCreationPermit();
147         return allocateWriteTransaction(TransactionType.WRITE_ONLY);
148     }
149
150     @Override
151     public void close() {
152         currentState = CLOSED_STATE;
153
154         // Send a close transaction chain request to each and every shard
155         getActorContext().broadcast(new CloseTransactionChain(transactionChainId).toSerializable());
156         parent.removeTransactionChain(this);
157     }
158
159     private TransactionProxy allocateWriteTransaction(final TransactionType type) {
160         State localState = currentState;
161         localState.checkReady();
162
163         final TransactionProxy ret = new TransactionProxy(this, type);
164         currentState = new Allocated(ret.getIdentifier(), localState.previousFuture());
165         return ret;
166     }
167
168     @Override
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);
172         return ret;
173     }
174
175     @Override
176     protected DataTree dataTreeForFactory(final LocalTransactionChain factory) {
177         return factory.getDataTree();
178     }
179
180     /**
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.
184      */
185     @Override
186     protected Future<PrimaryShardInfo> findPrimaryShard(final String shardName) {
187         // Read current state atomically
188         final State localState = currentState;
189
190         // There are no outstanding futures, shortcut
191         final Future<?> previous = localState.previousFuture();
192         if (previous == null) {
193             return parent.findPrimaryShard(shardName);
194         }
195
196         LOG.debug("Waiting for ready futures for on chain {}", getTransactionChainId());
197
198         // Add a callback for completion of the combined Futures.
199         final Promise<PrimaryShardInfo> returnPromise = akka.dispatch.Futures.promise();
200
201         final OnComplete onComplete = new OnComplete() {
202             @Override
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);
207                 } else {
208                     LOG.debug("Previous Tx readied - proceeding to FindPrimaryShard on chain {}",
209                             getTransactionChainId());
210
211                     // Send the FindPrimaryShard message and use the resulting Future to complete the
212                     // returned Promise.
213                     returnPromise.completeWith(parent.findPrimaryShard(shardName));
214                 }
215             }
216         };
217
218         previous.onComplete(onComplete, getActorContext().getClientDispatcher());
219         return returnPromise.future();
220     }
221
222     @Override
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);
228
229         // Transaction ready and we are not waiting for futures -- go to idle
230         if (cohortFutures.isEmpty()) {
231             currentState = IDLE_STATE;
232             return;
233         }
234
235         // Combine the ready Futures into 1
236         final Future<Iterable<T>> combined = akka.dispatch.Futures.sequence(
237                 cohortFutures, getActorContext().getClientDispatcher());
238
239         // Record the we have outstanding futures
240         final State newState = new Submitted(transaction, combined);
241         currentState = newState;
242
243         // Attach a completion reset, but only if we do not allocate a transaction
244         // in-between
245         combined.onComplete(new OnComplete<Iterable<T>>() {
246             @Override
247             public void onComplete(final Throwable arg0, final Iterable<T> arg1) {
248                 STATE_UPDATER.compareAndSet(TransactionChainProxy.this, newState, IDLE_STATE);
249             }
250         }, getActorContext().getClientDispatcher());
251     }
252
253     @Override
254     protected TransactionIdentifier nextIdentifier() {
255         return TransactionIdentifier.create(getMemberName(), TX_COUNTER.getAndIncrement(), transactionChainId);
256     }
257 }