2 * Copyright (c) 2016 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 com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Verify;
13 import com.google.common.primitives.UnsignedLong;
14 import com.google.common.util.concurrent.FutureCallback;
15 import java.util.ArrayDeque;
16 import java.util.Iterator;
17 import java.util.Queue;
18 import javax.annotation.Nullable;
19 import javax.annotation.concurrent.NotThreadSafe;
20 import org.opendaylight.controller.cluster.access.commands.CommitLocalTransactionRequest;
21 import org.opendaylight.controller.cluster.access.commands.ExistsTransactionRequest;
22 import org.opendaylight.controller.cluster.access.commands.ExistsTransactionSuccess;
23 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionRequest;
24 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionSuccess;
25 import org.opendaylight.controller.cluster.access.commands.OutOfOrderRequestException;
26 import org.opendaylight.controller.cluster.access.commands.PersistenceProtocol;
27 import org.opendaylight.controller.cluster.access.commands.ReadTransactionRequest;
28 import org.opendaylight.controller.cluster.access.commands.ReadTransactionSuccess;
29 import org.opendaylight.controller.cluster.access.commands.TransactionAbortRequest;
30 import org.opendaylight.controller.cluster.access.commands.TransactionAbortSuccess;
31 import org.opendaylight.controller.cluster.access.commands.TransactionCanCommitSuccess;
32 import org.opendaylight.controller.cluster.access.commands.TransactionCommitSuccess;
33 import org.opendaylight.controller.cluster.access.commands.TransactionDelete;
34 import org.opendaylight.controller.cluster.access.commands.TransactionDoCommitRequest;
35 import org.opendaylight.controller.cluster.access.commands.TransactionMerge;
36 import org.opendaylight.controller.cluster.access.commands.TransactionModification;
37 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitRequest;
38 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitSuccess;
39 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
40 import org.opendaylight.controller.cluster.access.commands.TransactionSuccess;
41 import org.opendaylight.controller.cluster.access.commands.TransactionWrite;
42 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
43 import org.opendaylight.controller.cluster.access.concepts.RequestException;
44 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
45 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
46 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
49 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * Frontend transaction state as observed by the shard leader.
56 * @author Robert Varga
59 final class FrontendTransaction {
60 private static final Logger LOG = LoggerFactory.getLogger(FrontendTransaction.class);
62 private final AbstractFrontendHistory history;
63 private final TransactionIdentifier id;
66 * It is possible that after we process a request and send a response that response gets lost and the client
67 * initiates a retry. Since subsequent requests can mutate transaction state we need to retain the response until
68 * it is acknowledged by the client.
70 private final Queue<Object> replayQueue = new ArrayDeque<>();
71 private long firstReplaySequence;
72 private Long lastPurgedSequence;
73 private long expectedSequence;
75 private ReadWriteShardDataTreeTransaction openTransaction;
76 private ModifyTransactionSuccess cachedModifySuccess;
77 private DataTreeModification sealedModification;
78 private ShardDataTreeCohort readyCohort;
80 private FrontendTransaction(final AbstractFrontendHistory history, final TransactionIdentifier id,
81 final ReadWriteShardDataTreeTransaction transaction) {
82 this.history = Preconditions.checkNotNull(history);
83 this.id = Preconditions.checkNotNull(id);
84 this.openTransaction = Preconditions.checkNotNull(transaction);
87 private FrontendTransaction(final AbstractFrontendHistory history, final TransactionIdentifier id,
88 final DataTreeModification mod) {
89 this.history = Preconditions.checkNotNull(history);
90 this.id = Preconditions.checkNotNull(id);
91 this.sealedModification = Preconditions.checkNotNull(mod);
94 static FrontendTransaction createOpen(final AbstractFrontendHistory history,
95 final ReadWriteShardDataTreeTransaction transaction) {
96 return new FrontendTransaction(history, transaction.getIdentifier(), transaction);
99 static FrontendTransaction createReady(final AbstractFrontendHistory history, final TransactionIdentifier id,
100 final DataTreeModification mod) {
101 return new FrontendTransaction(history, id, mod);
104 java.util.Optional<TransactionSuccess<?>> replaySequence(final long sequence) throws RequestException {
105 // Fast path check: if the requested sequence is the next request, bail early
106 if (expectedSequence == sequence) {
107 return java.util.Optional.empty();
110 // Check sequencing: we do not need to bother with future requests
111 if (Long.compareUnsigned(expectedSequence, sequence) < 0) {
112 throw new OutOfOrderRequestException(expectedSequence);
115 // Sanity check: if we have purged sequences, this has to be newer
116 if (lastPurgedSequence != null && Long.compareUnsigned(lastPurgedSequence.longValue(), sequence) >= 0) {
117 // Client has sent a request sequence, which has already been purged. This is a hard error, which should
118 // never occur. Throwing an IllegalArgumentException will cause it to be wrapped in a
119 // RuntimeRequestException (which is not retriable) and report it back to the client.
120 throw new IllegalArgumentException(String.format("Invalid purged sequence %s (last purged is %s)",
121 sequence, lastPurgedSequence));
124 // At this point we have established that the requested sequence lies in the open interval
125 // (lastPurgedSequence, expectedSequence). That does not actually mean we have a response, as the commit
126 // machinery is asynchronous, hence a reply may be in the works and not available.
128 long replaySequence = firstReplaySequence;
129 final Iterator<?> it = replayQueue.iterator();
130 while (it.hasNext()) {
131 final Object replay = it.next();
132 if (replaySequence == sequence) {
133 if (replay instanceof RequestException) {
134 throw (RequestException) replay;
137 Verify.verify(replay instanceof TransactionSuccess);
138 return java.util.Optional.of((TransactionSuccess<?>) replay);
145 return java.util.Optional.empty();
148 void purgeSequencesUpTo(final long sequence) {
149 // FIXME: implement this
151 lastPurgedSequence = sequence;
154 // Sequence has already been checked
155 @Nullable TransactionSuccess<?> handleRequest(final TransactionRequest<?> request, final RequestEnvelope envelope)
156 throws RequestException {
157 if (request instanceof ModifyTransactionRequest) {
158 return handleModifyTransaction((ModifyTransactionRequest) request, envelope);
159 } else if (request instanceof CommitLocalTransactionRequest) {
160 handleCommitLocalTransaction((CommitLocalTransactionRequest) request, envelope);
162 } else if (request instanceof ExistsTransactionRequest) {
163 return handleExistsTransaction((ExistsTransactionRequest) request);
164 } else if (request instanceof ReadTransactionRequest) {
165 return handleReadTransaction((ReadTransactionRequest) request);
166 } else if (request instanceof TransactionPreCommitRequest) {
167 handleTransactionPreCommit((TransactionPreCommitRequest) request, envelope);
169 } else if (request instanceof TransactionDoCommitRequest) {
170 handleTransactionDoCommit((TransactionDoCommitRequest) request, envelope);
172 } else if (request instanceof TransactionAbortRequest) {
173 handleTransactionAbort((TransactionAbortRequest) request, envelope);
176 throw new UnsupportedRequestException(request);
180 private void recordResponse(final long sequence, final Object response) {
181 if (replayQueue.isEmpty()) {
182 firstReplaySequence = sequence;
184 replayQueue.add(response);
188 private <T extends TransactionSuccess<?>> T recordSuccess(final long sequence, final T success) {
189 recordResponse(sequence, success);
193 private void recordAndSendSuccess(final RequestEnvelope envelope, final TransactionSuccess<?> success) {
194 recordResponse(success.getSequence(), success);
195 envelope.sendSuccess(success);
198 private void recordAndSendFailure(final RequestEnvelope envelope, final RuntimeRequestException failure) {
199 recordResponse(envelope.getMessage().getSequence(), failure);
200 envelope.sendFailure(failure);
203 private void handleTransactionPreCommit(final TransactionPreCommitRequest request,
204 final RequestEnvelope envelope) throws RequestException {
205 readyCohort.preCommit(new FutureCallback<DataTreeCandidate>() {
207 public void onSuccess(final DataTreeCandidate result) {
208 recordAndSendSuccess(envelope, new TransactionPreCommitSuccess(readyCohort.getIdentifier(),
209 request.getSequence()));
213 public void onFailure(final Throwable failure) {
214 recordAndSendFailure(envelope, new RuntimeRequestException("Precommit failed", failure));
220 private void handleTransactionDoCommit(final TransactionDoCommitRequest request, final RequestEnvelope envelope)
221 throws RequestException {
222 readyCohort.commit(new FutureCallback<UnsignedLong>() {
224 public void onSuccess(final UnsignedLong result) {
225 successfulCommit(envelope);
229 public void onFailure(final Throwable failure) {
230 recordAndSendFailure(envelope, new RuntimeRequestException("Commit failed", failure));
236 private void handleTransactionAbort(final TransactionAbortRequest request, final RequestEnvelope envelope)
237 throws RequestException {
238 readyCohort.abort(new FutureCallback<Void>() {
240 public void onSuccess(final Void result) {
242 recordAndSendSuccess(envelope, new TransactionAbortSuccess(id, request.getSequence()));
243 LOG.debug("Transaction {} aborted", id);
247 public void onFailure(final Throwable failure) {
249 LOG.warn("Transaction {} abort failed", id, failure);
250 recordAndSendFailure(envelope, new RuntimeRequestException("Abort failed", failure));
255 private void coordinatedCommit(final RequestEnvelope envelope) {
256 readyCohort.canCommit(new FutureCallback<Void>() {
258 public void onSuccess(final Void result) {
259 recordAndSendSuccess(envelope, new TransactionCanCommitSuccess(readyCohort.getIdentifier(),
260 envelope.getMessage().getSequence()));
264 public void onFailure(final Throwable failure) {
265 recordAndSendFailure(envelope, new RuntimeRequestException("CanCommit failed", failure));
271 private void directCommit(final RequestEnvelope envelope) {
272 readyCohort.canCommit(new FutureCallback<Void>() {
274 public void onSuccess(final Void result) {
275 successfulDirectCanCommit(envelope);
279 public void onFailure(final Throwable failure) {
280 recordAndSendFailure(envelope, new RuntimeRequestException("CanCommit failed", failure));
287 private void successfulDirectCanCommit(final RequestEnvelope envelope) {
288 readyCohort.preCommit(new FutureCallback<DataTreeCandidate>() {
290 public void onSuccess(final DataTreeCandidate result) {
291 successfulDirectPreCommit(envelope);
295 public void onFailure(final Throwable failure) {
296 recordAndSendFailure(envelope, new RuntimeRequestException("PreCommit failed", failure));
302 private void successfulDirectPreCommit(final RequestEnvelope envelope) {
303 readyCohort.commit(new FutureCallback<UnsignedLong>() {
306 public void onSuccess(final UnsignedLong result) {
307 successfulCommit(envelope);
311 public void onFailure(final Throwable failure) {
312 recordAndSendFailure(envelope, new RuntimeRequestException("DoCommit failed", failure));
318 private void successfulCommit(final RequestEnvelope envelope) {
319 recordAndSendSuccess(envelope, new TransactionCommitSuccess(readyCohort.getIdentifier(),
320 envelope.getMessage().getSequence()));
324 private void handleCommitLocalTransaction(final CommitLocalTransactionRequest request,
325 final RequestEnvelope envelope) throws RequestException {
326 if (sealedModification.equals(request.getModification())) {
327 readyCohort = history.createReadyCohort(id, sealedModification);
329 if (request.isCoordinated()) {
330 coordinatedCommit(envelope);
332 directCommit(envelope);
335 throw new UnsupportedRequestException(request);
339 private ExistsTransactionSuccess handleExistsTransaction(final ExistsTransactionRequest request)
340 throws RequestException {
341 final Optional<NormalizedNode<?, ?>> data = openTransaction.getSnapshot().readNode(request.getPath());
342 return recordSuccess(request.getSequence(), new ExistsTransactionSuccess(id, request.getSequence(),
346 private ReadTransactionSuccess handleReadTransaction(final ReadTransactionRequest request) throws RequestException {
347 final Optional<NormalizedNode<?, ?>> data = openTransaction.getSnapshot().readNode(request.getPath());
348 return recordSuccess(request.getSequence(), new ReadTransactionSuccess(id, request.getSequence(), data));
351 private ModifyTransactionSuccess replyModifySuccess(final long sequence) {
352 if (cachedModifySuccess == null) {
353 cachedModifySuccess = new ModifyTransactionSuccess(id, sequence);
356 return recordSuccess(sequence, cachedModifySuccess);
359 private @Nullable TransactionSuccess<?> handleModifyTransaction(final ModifyTransactionRequest request,
360 final RequestEnvelope envelope) throws RequestException {
362 final DataTreeModification modification = openTransaction.getSnapshot();
363 for (TransactionModification m : request.getModifications()) {
364 if (m instanceof TransactionDelete) {
365 modification.delete(m.getPath());
366 } else if (m instanceof TransactionWrite) {
367 modification.write(m.getPath(), ((TransactionWrite) m).getData());
368 } else if (m instanceof TransactionMerge) {
369 modification.merge(m.getPath(), ((TransactionMerge) m).getData());
371 LOG.warn("{}: ignoring unhandled modification {}", history.persistenceId(), m);
375 final java.util.Optional<PersistenceProtocol> maybeProto = request.getPersistenceProtocol();
376 if (!maybeProto.isPresent()) {
377 return replyModifySuccess(request.getSequence());
380 switch (maybeProto.get()) {
382 openTransaction.abort();
383 openTransaction = null;
384 return replyModifySuccess(request.getSequence());
386 readyCohort = openTransaction.ready();
387 openTransaction = null;
388 directCommit(envelope);
391 readyCohort = openTransaction.ready();
392 openTransaction = null;
393 coordinatedCommit(envelope);
396 throw new UnsupportedRequestException(request);