2 * Copyright (c) 2016, 2017 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.MoreObjects;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Verify;
13 import java.util.ArrayDeque;
14 import java.util.Optional;
15 import java.util.Queue;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.opendaylight.controller.cluster.access.commands.IncrementTransactionSequenceRequest;
18 import org.opendaylight.controller.cluster.access.commands.IncrementTransactionSequenceSuccess;
19 import org.opendaylight.controller.cluster.access.commands.OutOfOrderRequestException;
20 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
21 import org.opendaylight.controller.cluster.access.commands.TransactionSuccess;
22 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
23 import org.opendaylight.controller.cluster.access.concepts.RequestException;
24 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
25 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
26 import org.opendaylight.yangtools.concepts.Identifiable;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
31 * Frontend common transaction state as observed by the shard leader. This class is NOT thread-safe.
33 * @author Robert Varga
35 abstract class FrontendTransaction implements Identifiable<TransactionIdentifier> {
36 private static final Logger LOG = LoggerFactory.getLogger(FrontendTransaction.class);
38 private final AbstractFrontendHistory history;
39 private final TransactionIdentifier id;
42 * It is possible that after we process a request and send a response that response gets lost and the client
43 * initiates a retry. Since subsequent requests can mutate transaction state we need to retain the response until
44 * it is acknowledged by the client.
46 private final Queue<Object> replayQueue = new ArrayDeque<>();
47 private long firstReplaySequence;
48 private Long lastPurgedSequence;
49 private long expectedSequence;
51 private RequestException previousFailure;
53 FrontendTransaction(final AbstractFrontendHistory history, final TransactionIdentifier id) {
54 this.history = Preconditions.checkNotNull(history);
55 this.id = Preconditions.checkNotNull(id);
59 public final TransactionIdentifier getIdentifier() {
63 final AbstractFrontendHistory history() {
67 final String persistenceId() {
68 return history().persistenceId();
71 final Optional<TransactionSuccess<?>> replaySequence(final long sequence) throws RequestException {
72 // Fast path check: if the requested sequence is the next request, bail early
73 if (expectedSequence == sequence) {
74 return Optional.empty();
77 // Check sequencing: we do not need to bother with future requests
78 if (Long.compareUnsigned(expectedSequence, sequence) < 0) {
79 throw new OutOfOrderRequestException(expectedSequence);
82 // Sanity check: if we have purged sequences, this has to be newer
83 if (lastPurgedSequence != null && Long.compareUnsigned(lastPurgedSequence.longValue(), sequence) >= 0) {
84 // Client has sent a request sequence, which has already been purged. This is a hard error, which should
85 // never occur. Throwing an IllegalArgumentException will cause it to be wrapped in a
86 // RuntimeRequestException (which is not retriable) and report it back to the client.
87 throw new IllegalArgumentException(String.format("Invalid purged sequence %s (last purged is %s)",
88 sequence, lastPurgedSequence));
91 // At this point we have established that the requested sequence lies in the open interval
92 // (lastPurgedSequence, expectedSequence). That does not actually mean we have a response, as the commit
93 // machinery is asynchronous, hence a reply may be in the works and not available.
95 long replaySequence = firstReplaySequence;
96 for (Object replay : replayQueue) {
97 if (replaySequence == sequence) {
98 if (replay instanceof RequestException) {
99 throw (RequestException) replay;
102 Verify.verify(replay instanceof TransactionSuccess);
103 return Optional.of((TransactionSuccess<?>) replay);
110 return Optional.empty();
113 final void purgeSequencesUpTo(final long sequence) {
114 // FIXME: implement this
116 lastPurgedSequence = sequence;
119 // Request order has already been checked by caller and replaySequence()
120 @SuppressWarnings("checkstyle:IllegalCatch")
121 final @Nullable TransactionSuccess<?> handleRequest(final TransactionRequest<?> request,
122 final RequestEnvelope envelope, final long now) throws RequestException {
123 if (request instanceof IncrementTransactionSequenceRequest) {
124 final IncrementTransactionSequenceRequest incr = (IncrementTransactionSequenceRequest) request;
125 expectedSequence += incr.getIncrement();
127 return recordSuccess(incr.getSequence(),
128 new IncrementTransactionSequenceSuccess(incr.getTarget(), incr.getSequence()));
131 if (previousFailure != null) {
132 LOG.debug("{}: Rejecting request {} due to previous failure", persistenceId(), request, previousFailure);
133 throw previousFailure;
137 return doHandleRequest(request, envelope, now);
138 } catch (RuntimeException e) {
140 * The request failed to process, we should not attempt to ever
141 * apply it again. Furthermore we cannot accept any further requests
142 * from this connection, simply because the transaction state is
145 LOG.debug("{}: Request {} failed to process", persistenceId(), request, e);
146 previousFailure = new RuntimeRequestException("Request " + request + " failed to process", e);
147 throw previousFailure;
151 abstract @Nullable TransactionSuccess<?> doHandleRequest(TransactionRequest<?> request, RequestEnvelope envelope,
152 long now) throws RequestException;
154 abstract void retire();
156 private void recordResponse(final long sequence, final Object response) {
157 if (replayQueue.isEmpty()) {
158 firstReplaySequence = sequence;
160 replayQueue.add(response);
164 final <T extends TransactionSuccess<?>> T recordSuccess(final long sequence, final T success) {
165 recordResponse(sequence, success);
169 private long executionTime(final long startTime) {
170 return history.readTime() - startTime;
173 final void recordAndSendSuccess(final RequestEnvelope envelope, final long startTime,
174 final TransactionSuccess<?> success) {
175 recordResponse(success.getSequence(), success);
176 envelope.sendSuccess(success, executionTime(startTime));
179 final void recordAndSendFailure(final RequestEnvelope envelope, final long startTime,
180 final RuntimeRequestException failure) {
181 recordResponse(envelope.getMessage().getSequence(), failure);
182 envelope.sendFailure(failure, executionTime(startTime));
186 public final String toString() {
187 return MoreObjects.toStringHelper(this).omitNullValues().add("identifier", getIdentifier())
188 .add("expectedSequence", expectedSequence).add("firstReplaySequence", firstReplaySequence)
189 .add("lastPurgedSequence", lastPurgedSequence)