ff6471caa0637ebfc21b7fc6947909a02c63bbe4
[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     }
157
158     private TransactionProxy allocateWriteTransaction(final TransactionType type) {
159         State localState = currentState;
160         localState.checkReady();
161
162         final TransactionProxy ret = new TransactionProxy(this, type);
163         currentState = new Allocated(ret.getIdentifier(), localState.previousFuture());
164         return ret;
165     }
166
167     @Override
168     protected LocalTransactionChain factoryForShard(final String shardName, final ActorSelection shardLeader, final DataTree dataTree) {
169         final LocalTransactionChain ret = new LocalTransactionChain(this, shardLeader, dataTree);
170         LOG.debug("Allocated transaction chain {} for shard {} leader {}", ret, shardName, shardLeader);
171         return ret;
172     }
173
174     /**
175      * This method is overridden to ensure the previous Tx's ready operations complete
176      * before we initiate the next Tx in the chain to avoid creation failures if the
177      * previous Tx's ready operations haven't completed yet.
178      */
179     @Override
180     protected Future<PrimaryShardInfo> findPrimaryShard(final String shardName) {
181         // Read current state atomically
182         final State localState = currentState;
183
184         // There are no outstanding futures, shortcut
185         final Future<?> previous = localState.previousFuture();
186         if (previous == null) {
187             return parent.findPrimaryShard(shardName);
188         }
189
190         LOG.debug("Waiting for ready futures for on chain {}", getTransactionChainId());
191
192         // Add a callback for completion of the combined Futures.
193         final Promise<PrimaryShardInfo> returnPromise = akka.dispatch.Futures.promise();
194
195         final OnComplete onComplete = new OnComplete() {
196             @Override
197             public void onComplete(final Throwable failure, final Object notUsed) {
198                 if (failure != null) {
199                     // A Ready Future failed so fail the returned Promise.
200                     returnPromise.failure(failure);
201                 } else {
202                     LOG.debug("Previous Tx readied - proceeding to FindPrimaryShard on chain {}",
203                             getTransactionChainId());
204
205                     // Send the FindPrimaryShard message and use the resulting Future to complete the
206                     // returned Promise.
207                     returnPromise.completeWith(parent.findPrimaryShard(shardName));
208                 }
209             }
210         };
211
212         previous.onComplete(onComplete, getActorContext().getClientDispatcher());
213         return returnPromise.future();
214     }
215
216     @Override
217     protected <T> void onTransactionReady(final TransactionIdentifier transaction, final Collection<Future<T>> cohortFutures) {
218         final State localState = currentState;
219         Preconditions.checkState(localState instanceof Allocated, "Readying transaction %s while state is %s", transaction, localState);
220         final TransactionIdentifier currentTx = ((Allocated)localState).getIdentifier();
221         Preconditions.checkState(transaction.equals(currentTx), "Readying transaction %s while %s is allocated", transaction, currentTx);
222
223         // Transaction ready and we are not waiting for futures -- go to idle
224         if (cohortFutures.isEmpty()) {
225             currentState = IDLE_STATE;
226             return;
227         }
228
229         // Combine the ready Futures into 1
230         final Future<Iterable<T>> combined = akka.dispatch.Futures.sequence(
231                 cohortFutures, getActorContext().getClientDispatcher());
232
233         // Record the we have outstanding futures
234         final State newState = new Submitted(transaction, combined);
235         currentState = newState;
236
237         // Attach a completion reset, but only if we do not allocate a transaction
238         // in-between
239         combined.onComplete(new OnComplete<Iterable<T>>() {
240             @Override
241             public void onComplete(final Throwable arg0, final Iterable<T> arg1) {
242                 STATE_UPDATER.compareAndSet(TransactionChainProxy.this, newState, IDLE_STATE);
243             }
244         }, getActorContext().getClientDispatcher());
245     }
246
247     @Override
248     protected TransactionIdentifier nextIdentifier() {
249         return TransactionIdentifier.create(getMemberName(), TX_COUNTER.getAndIncrement(), transactionChainId);
250     }
251 }