099095325c2a97cb452858f2cf60957a09f2c31e
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / FrontendReadWriteTransaction.java
1 /*
2  * Copyright (c) 2016 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 com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.primitives.UnsignedLong;
13 import com.google.common.util.concurrent.FutureCallback;
14 import java.util.Collection;
15 import javax.annotation.Nullable;
16 import javax.annotation.concurrent.NotThreadSafe;
17 import org.opendaylight.controller.cluster.access.commands.CommitLocalTransactionRequest;
18 import org.opendaylight.controller.cluster.access.commands.ExistsTransactionRequest;
19 import org.opendaylight.controller.cluster.access.commands.ExistsTransactionSuccess;
20 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionRequest;
21 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionSuccess;
22 import org.opendaylight.controller.cluster.access.commands.PersistenceProtocol;
23 import org.opendaylight.controller.cluster.access.commands.ReadTransactionRequest;
24 import org.opendaylight.controller.cluster.access.commands.ReadTransactionSuccess;
25 import org.opendaylight.controller.cluster.access.commands.TransactionAbortRequest;
26 import org.opendaylight.controller.cluster.access.commands.TransactionAbortSuccess;
27 import org.opendaylight.controller.cluster.access.commands.TransactionCanCommitSuccess;
28 import org.opendaylight.controller.cluster.access.commands.TransactionCommitSuccess;
29 import org.opendaylight.controller.cluster.access.commands.TransactionDelete;
30 import org.opendaylight.controller.cluster.access.commands.TransactionDoCommitRequest;
31 import org.opendaylight.controller.cluster.access.commands.TransactionMerge;
32 import org.opendaylight.controller.cluster.access.commands.TransactionModification;
33 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitRequest;
34 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitSuccess;
35 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
36 import org.opendaylight.controller.cluster.access.commands.TransactionSuccess;
37 import org.opendaylight.controller.cluster.access.commands.TransactionWrite;
38 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
39 import org.opendaylight.controller.cluster.access.concepts.RequestException;
40 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
41 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
42 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
45 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * Frontend read-write transaction state as observed by the shard leader.
51  *
52  * @author Robert Varga
53  */
54 @NotThreadSafe
55 final class FrontendReadWriteTransaction extends FrontendTransaction {
56     private static final Logger LOG = LoggerFactory.getLogger(FrontendReadWriteTransaction.class);
57
58     private ReadWriteShardDataTreeTransaction openTransaction;
59     private DataTreeModification sealedModification;
60     private ShardDataTreeCohort readyCohort;
61
62     private FrontendReadWriteTransaction(final AbstractFrontendHistory history, final TransactionIdentifier id,
63             final ReadWriteShardDataTreeTransaction transaction) {
64         super(history, id);
65         this.openTransaction = Preconditions.checkNotNull(transaction);
66     }
67
68     private FrontendReadWriteTransaction(final AbstractFrontendHistory history, final TransactionIdentifier id,
69             final DataTreeModification mod) {
70         super(history, id);
71         this.sealedModification = Preconditions.checkNotNull(mod);
72     }
73
74     static FrontendReadWriteTransaction createOpen(final AbstractFrontendHistory history,
75             final ReadWriteShardDataTreeTransaction transaction) {
76         return new FrontendReadWriteTransaction(history, transaction.getIdentifier(), transaction);
77     }
78
79     static FrontendReadWriteTransaction createReady(final AbstractFrontendHistory history,
80             final TransactionIdentifier id, final DataTreeModification mod) {
81         return new FrontendReadWriteTransaction(history, id, mod);
82     }
83
84     // Sequence has already been checked
85     @Override
86     @Nullable TransactionSuccess<?> handleRequest(final TransactionRequest<?> request, final RequestEnvelope envelope,
87             final long now) throws RequestException {
88         if (request instanceof ModifyTransactionRequest) {
89             return handleModifyTransaction((ModifyTransactionRequest) request, envelope, now);
90         } else if (request instanceof CommitLocalTransactionRequest) {
91             handleCommitLocalTransaction((CommitLocalTransactionRequest) request, envelope, now);
92             return null;
93         } else if (request instanceof ExistsTransactionRequest) {
94             return handleExistsTransaction((ExistsTransactionRequest) request);
95         } else if (request instanceof ReadTransactionRequest) {
96             return handleReadTransaction((ReadTransactionRequest) request);
97         } else if (request instanceof TransactionPreCommitRequest) {
98             handleTransactionPreCommit((TransactionPreCommitRequest) request, envelope, now);
99             return null;
100         } else if (request instanceof TransactionDoCommitRequest) {
101             handleTransactionDoCommit((TransactionDoCommitRequest) request, envelope, now);
102             return null;
103         } else if (request instanceof TransactionAbortRequest) {
104             handleTransactionAbort((TransactionAbortRequest) request, envelope, now);
105             return null;
106         } else {
107             throw new UnsupportedRequestException(request);
108         }
109     }
110
111     private void handleTransactionPreCommit(final TransactionPreCommitRequest request,
112             final RequestEnvelope envelope, final long now) throws RequestException {
113         readyCohort.preCommit(new FutureCallback<DataTreeCandidate>() {
114             @Override
115             public void onSuccess(final DataTreeCandidate result) {
116                 recordAndSendSuccess(envelope, now, new TransactionPreCommitSuccess(readyCohort.getIdentifier(),
117                     request.getSequence()));
118             }
119
120             @Override
121             public void onFailure(final Throwable failure) {
122                 recordAndSendFailure(envelope, now, new RuntimeRequestException("Precommit failed", failure));
123                 readyCohort = null;
124             }
125         });
126     }
127
128     private void handleTransactionDoCommit(final TransactionDoCommitRequest request, final RequestEnvelope envelope,
129             final long now) throws RequestException {
130         readyCohort.commit(new FutureCallback<UnsignedLong>() {
131             @Override
132             public void onSuccess(final UnsignedLong result) {
133                 successfulCommit(envelope, now);
134             }
135
136             @Override
137             public void onFailure(final Throwable failure) {
138                 recordAndSendFailure(envelope, now, new RuntimeRequestException("Commit failed", failure));
139                 readyCohort = null;
140             }
141         });
142     }
143
144     private void handleTransactionAbort(final TransactionAbortRequest request,
145             final RequestEnvelope envelope, final long now) throws RequestException {
146         if (readyCohort == null) {
147             openTransaction.abort(() -> recordAndSendSuccess(envelope, now,
148                 new TransactionAbortSuccess(getIdentifier(), request.getSequence())));
149             return;
150         }
151
152         readyCohort.abort(new FutureCallback<Void>() {
153             @Override
154             public void onSuccess(final Void result) {
155                 readyCohort = null;
156                 recordAndSendSuccess(envelope, now, new TransactionAbortSuccess(getIdentifier(),
157                     request.getSequence()));
158                 LOG.debug("Transaction {} aborted", getIdentifier());
159             }
160
161             @Override
162             public void onFailure(final Throwable failure) {
163                 readyCohort = null;
164                 LOG.warn("Transaction {} abort failed", getIdentifier(), failure);
165                 recordAndSendFailure(envelope, now, new RuntimeRequestException("Abort failed", failure));
166             }
167         });
168     }
169
170     private void coordinatedCommit(final RequestEnvelope envelope, final long now) {
171         readyCohort.canCommit(new FutureCallback<Void>() {
172             @Override
173             public void onSuccess(final Void result) {
174                 recordAndSendSuccess(envelope, now, new TransactionCanCommitSuccess(readyCohort.getIdentifier(),
175                     envelope.getMessage().getSequence()));
176             }
177
178             @Override
179             public void onFailure(final Throwable failure) {
180                 recordAndSendFailure(envelope, now, new RuntimeRequestException("CanCommit failed", failure));
181                 readyCohort = null;
182             }
183         });
184     }
185
186     private void directCommit(final RequestEnvelope envelope, final long now) {
187         readyCohort.canCommit(new FutureCallback<Void>() {
188             @Override
189             public void onSuccess(final Void result) {
190                 successfulDirectCanCommit(envelope, now);
191             }
192
193             @Override
194             public void onFailure(final Throwable failure) {
195                 recordAndSendFailure(envelope, now, new RuntimeRequestException("CanCommit failed", failure));
196                 readyCohort = null;
197             }
198         });
199     }
200
201     private void successfulDirectCanCommit(final RequestEnvelope envelope, final long startTime) {
202         readyCohort.preCommit(new FutureCallback<DataTreeCandidate>() {
203             @Override
204             public void onSuccess(final DataTreeCandidate result) {
205                 successfulDirectPreCommit(envelope, startTime);
206             }
207
208             @Override
209             public void onFailure(final Throwable failure) {
210                 recordAndSendFailure(envelope, startTime, new RuntimeRequestException("PreCommit failed", failure));
211                 readyCohort = null;
212             }
213         });
214     }
215
216     private void successfulDirectPreCommit(final RequestEnvelope envelope, final long startTime) {
217         readyCohort.commit(new FutureCallback<UnsignedLong>() {
218             @Override
219             public void onSuccess(final UnsignedLong result) {
220                 successfulCommit(envelope, startTime);
221             }
222
223             @Override
224             public void onFailure(final Throwable failure) {
225                 recordAndSendFailure(envelope, startTime, new RuntimeRequestException("DoCommit failed", failure));
226                 readyCohort = null;
227             }
228         });
229     }
230
231     private void successfulCommit(final RequestEnvelope envelope, final long startTime) {
232         recordAndSendSuccess(envelope, startTime, new TransactionCommitSuccess(readyCohort.getIdentifier(),
233             envelope.getMessage().getSequence()));
234         readyCohort = null;
235     }
236
237     private void handleCommitLocalTransaction(final CommitLocalTransactionRequest request,
238             final RequestEnvelope envelope, final long now) throws RequestException {
239         if (!sealedModification.equals(request.getModification())) {
240             LOG.warn("Expecting modification {}, commit request has {}", sealedModification, request.getModification());
241             throw new UnsupportedRequestException(request);
242         }
243
244         final java.util.Optional<Exception> optFailure = request.getDelayedFailure();
245         if (optFailure.isPresent()) {
246             readyCohort = history().createFailedCohort(getIdentifier(), sealedModification, optFailure.get());
247         } else {
248             readyCohort = history().createReadyCohort(getIdentifier(), sealedModification);
249         }
250
251         if (request.isCoordinated()) {
252             coordinatedCommit(envelope, now);
253         } else {
254             directCommit(envelope, now);
255         }
256     }
257
258     private ExistsTransactionSuccess handleExistsTransaction(final ExistsTransactionRequest request)
259             throws RequestException {
260         final Optional<NormalizedNode<?, ?>> data = openTransaction.getSnapshot().readNode(request.getPath());
261         return recordSuccess(request.getSequence(), new ExistsTransactionSuccess(getIdentifier(), request.getSequence(),
262             data.isPresent()));
263     }
264
265     private ReadTransactionSuccess handleReadTransaction(final ReadTransactionRequest request)
266             throws RequestException {
267         final Optional<NormalizedNode<?, ?>> data = openTransaction.getSnapshot().readNode(request.getPath());
268         return recordSuccess(request.getSequence(), new ReadTransactionSuccess(getIdentifier(), request.getSequence(),
269             data));
270     }
271
272     private ModifyTransactionSuccess replyModifySuccess(final long sequence) {
273         return recordSuccess(sequence, new ModifyTransactionSuccess(getIdentifier(), sequence));
274     }
275
276     private @Nullable TransactionSuccess<?> handleModifyTransaction(final ModifyTransactionRequest request,
277             final RequestEnvelope envelope, final long now) throws RequestException {
278
279         final Collection<TransactionModification> mods = request.getModifications();
280         if (!mods.isEmpty()) {
281             final DataTreeModification modification = openTransaction.getSnapshot();
282             for (TransactionModification m : mods) {
283                 if (m instanceof TransactionDelete) {
284                     modification.delete(m.getPath());
285                 } else if (m instanceof TransactionWrite) {
286                     modification.write(m.getPath(), ((TransactionWrite) m).getData());
287                 } else if (m instanceof TransactionMerge) {
288                     modification.merge(m.getPath(), ((TransactionMerge) m).getData());
289                 } else {
290                     LOG.warn("{}: ignoring unhandled modification {}", history().persistenceId(), m);
291                 }
292             }
293         }
294
295         final java.util.Optional<PersistenceProtocol> maybeProto = request.getPersistenceProtocol();
296         if (!maybeProto.isPresent()) {
297             return replyModifySuccess(request.getSequence());
298         }
299
300         switch (maybeProto.get()) {
301             case ABORT:
302                 openTransaction.abort(() -> replyModifySuccess(request.getSequence()));
303                 openTransaction = null;
304                 return null;
305             case READY:
306                 ensureReady();
307                 return replyModifySuccess(request.getSequence());
308             case SIMPLE:
309                 ensureReady();
310                 directCommit(envelope, now);
311                 return null;
312             case THREE_PHASE:
313                 ensureReady();
314                 coordinatedCommit(envelope, now);
315                 return null;
316             default:
317                 throw new UnsupportedRequestException(request);
318         }
319     }
320
321     private void ensureReady() {
322         // We may have a combination of READY + SIMPLE/THREE_PHASE , in which case we want to ready the transaction
323         // only once.
324         if (readyCohort == null) {
325             readyCohort = openTransaction.ready();
326             LOG.debug("{}: transitioned {} to ready", history().persistenceId(), openTransaction.getIdentifier());
327             openTransaction = null;
328         }
329     }
330 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.