BUG-2255: introduce PingPongDataBroker
[controller.git] / opendaylight / md-sal / sal-dom-broker / src / main / java / org / opendaylight / controller / md / sal / dom / broker / impl / PingPongTransactionChain.java
1 /*
2  * Copyright (c) 2014 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.md.sal.dom.broker.impl;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import javax.annotation.concurrent.GuardedBy;
17 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
18 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
19 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
20 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
21 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
22 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
23 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
24 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
25 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
28 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
29 import org.opendaylight.controller.md.sal.dom.spi.ForwardingDOMDataReadWriteTransaction;
30 import org.opendaylight.yangtools.yang.common.RpcResult;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * An implementation of {@link DOMTransactionChain}, which has a very specific
38  * behavior, which some users may find surprising. If keeps the general
39  * intent of the contract, but it makes sure there are never more than two
40  * transactions allocated at any given time: one of them is being committed,
41  * and while that is happening, the other one acts as the scratch pad. Once
42  * the committing transaction completes successfully, the scratch transaction
43  * is enqueued as soon as it is ready.
44  *
45  * This mode of operation means that there is no inherent isolation between
46  * the front-end transactions and transactions cannot be reasonably cancelled.
47  *
48  * It furthermore means that the transactions returned by {@link #newReadOnlyTransaction()}
49  * counts as an outstanding transaction and the user may not allocate multiple
50  * read-only transactions at the same time.
51  */
52 public final class PingPongTransactionChain implements DOMTransactionChain {
53     private static final Logger LOG = LoggerFactory.getLogger(PingPongTransactionChain.class);
54     private final DOMTransactionChain delegate;
55
56     @GuardedBy("this")
57     private PingPongTransaction bufferTransaction;
58     @GuardedBy("this")
59     private PingPongTransaction inflightTransaction;
60     @GuardedBy("this")
61     private boolean haveLocked;
62     @GuardedBy("this")
63     private boolean failed;
64
65     PingPongTransactionChain(final DOMDataBroker broker, final TransactionChainListener listener) {
66         this.delegate = broker.createTransactionChain(new TransactionChainListener() {
67             @Override
68             public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
69                 LOG.debug("Delegate chain {} reported failure in {}", chain, transaction, cause);
70
71                 final DOMDataReadWriteTransaction frontend;
72                 if (inflightTransaction == null) {
73                     LOG.warn("Transaction chain {} failed with no pending transactions", chain);
74                     frontend = null;
75                 } else {
76                     frontend = inflightTransaction.getFrontendTransaction();
77                 }
78
79                 listener.onTransactionChainFailed(PingPongTransactionChain.this, frontend , cause);
80                 delegateFailed();
81             }
82
83             @Override
84             public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
85                 listener.onTransactionChainSuccessful(PingPongTransactionChain.this);
86             }
87         });
88     }
89
90     private synchronized void delegateFailed() {
91         failed = true;
92         if (!haveLocked) {
93             processBuffer();
94         }
95     }
96
97     private synchronized PingPongTransaction allocateTransaction() {
98         Preconditions.checkState(!haveLocked, "Attempted to start a transaction while a previous one is still outstanding");
99         Preconditions.checkState(!failed, "Attempted to use a failed chain");
100
101         if (bufferTransaction == null) {
102             bufferTransaction = new PingPongTransaction(delegate.newReadWriteTransaction());
103         }
104
105         haveLocked = true;
106         return bufferTransaction;
107     }
108
109     @GuardedBy("this")
110     private void processBuffer() {
111         final PingPongTransaction tx = bufferTransaction;
112
113         if (tx != null) {
114             if (failed) {
115                 LOG.debug("Cancelling transaction {}", tx);
116                 tx.getTransaction().cancel();
117                 bufferTransaction = null;
118                 return;
119             }
120
121             LOG.debug("Submitting transaction {}", tx);
122             final CheckedFuture<Void, ?> f = tx.getTransaction().submit();
123             bufferTransaction = null;
124             inflightTransaction = tx;
125
126             Futures.addCallback(f, new FutureCallback<Void>() {
127                 @Override
128                 public void onSuccess(final Void result) {
129                     transactionSuccessful(tx, result);
130                 }
131
132                 @Override
133                 public void onFailure(final Throwable t) {
134                     transactionFailed(tx, t);
135                 }
136             });
137         }
138     }
139
140     private void transactionSuccessful(final PingPongTransaction tx, final Void result) {
141         LOG.debug("Transaction {} completed successfully", tx);
142
143         synchronized (this) {
144             Preconditions.checkState(inflightTransaction == tx, "Successful transaction %s while %s was submitted", tx, inflightTransaction);
145             inflightTransaction = null;
146
147             if (!haveLocked) {
148                 processBuffer();
149             }
150         }
151
152         // Can run unsynchronized
153         tx.onSuccess(result);
154     }
155
156     private void transactionFailed(final PingPongTransaction tx, final Throwable t) {
157         LOG.debug("Transaction {} failed", tx, t);
158
159         synchronized (this) {
160             Preconditions.checkState(inflightTransaction == tx, "Failed transaction %s while %s was submitted", tx, inflightTransaction);
161             inflightTransaction = null;
162         }
163
164         tx.onFailure(t);
165     }
166
167     private synchronized void readyTransaction(final PingPongTransaction tx) {
168         Preconditions.checkState(haveLocked, "Attempted to submit transaction while it is not outstanding");
169         Preconditions.checkState(bufferTransaction == tx, "Attempted to submit transaction %s while we have %s", tx, bufferTransaction);
170
171         haveLocked = false;
172         LOG.debug("Transaction {} unlocked", bufferTransaction);
173
174         if (inflightTransaction == null) {
175             processBuffer();
176         }
177     }
178
179     @Override
180     public synchronized void close() {
181         Preconditions.checkState(!haveLocked, "Attempted to close chain while a transaction is outstanding");
182         processBuffer();
183         delegate.close();
184     }
185
186     @Override
187     public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
188         final PingPongTransaction tx = allocateTransaction();
189
190         return new DOMDataReadOnlyTransaction() {
191             @Override
192             public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
193                     final YangInstanceIdentifier path) {
194                 return tx.getTransaction().read(store, path);
195             }
196
197             @Override
198             public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
199                     final YangInstanceIdentifier path) {
200                 return tx.getTransaction().exists(store, path);
201             }
202
203             @Override
204             public Object getIdentifier() {
205                 return tx.getTransaction().getIdentifier();
206             }
207
208             @Override
209             public void close() {
210                 readyTransaction(tx);
211             }
212         };
213     }
214
215     @Override
216     public DOMDataReadWriteTransaction newReadWriteTransaction() {
217         final PingPongTransaction tx = allocateTransaction();
218         final DOMDataReadWriteTransaction ret = new ForwardingDOMDataReadWriteTransaction() {
219             @Override
220             protected DOMDataReadWriteTransaction delegate() {
221                 return tx.getTransaction();
222             }
223
224             @Override
225             public CheckedFuture<Void, TransactionCommitFailedException> submit() {
226                 readyTransaction(tx);
227                 return tx.getSubmitFuture();
228             }
229
230             @Override
231             public ListenableFuture<RpcResult<TransactionStatus>> commit() {
232                 readyTransaction(tx);
233                 return tx.getCommitFuture();
234             }
235
236             @Override
237             public boolean cancel() {
238                 throw new UnsupportedOperationException("Transaction cancellation is not supported");
239             }
240         };
241
242         tx.recordFrontendTransaction(ret);
243         return ret;
244     }
245
246     @Override
247     public DOMDataWriteTransaction newWriteOnlyTransaction() {
248         return newReadWriteTransaction();
249     }
250 }