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.MoreObjects;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Verify;
13 import java.util.ArrayDeque;
14 import java.util.Iterator;
15 import java.util.Queue;
16 import javax.annotation.Nullable;
17 import javax.annotation.concurrent.NotThreadSafe;
18 import org.opendaylight.controller.cluster.access.commands.OutOfOrderRequestException;
19 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
20 import org.opendaylight.controller.cluster.access.commands.TransactionSuccess;
21 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
22 import org.opendaylight.controller.cluster.access.concepts.RequestException;
23 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
24 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
25 import org.opendaylight.yangtools.concepts.Identifiable;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
30 * Frontend common transaction state as observed by the shard leader.
32 * @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 java.util.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 java.util.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 final Iterator<?> it = replayQueue.iterator();
97 while (it.hasNext()) {
98 final Object replay = it.next();
99 if (replaySequence == sequence) {
100 if (replay instanceof RequestException) {
101 throw (RequestException) replay;
104 Verify.verify(replay instanceof TransactionSuccess);
105 return java.util.Optional.of((TransactionSuccess<?>) replay);
112 return java.util.Optional.empty();
115 final void purgeSequencesUpTo(final long sequence) {
116 // FIXME: implement this
118 lastPurgedSequence = sequence;
121 // Request order has already been checked by caller and replaySequence()
122 @SuppressWarnings("checkstyle:IllegalCatch")
123 final @Nullable TransactionSuccess<?> handleRequest(final TransactionRequest<?> request,
124 final RequestEnvelope envelope, final long now) throws RequestException {
125 if (previousFailure != null) {
126 LOG.debug("{}: Rejecting request {} due to previous failure", persistenceId(), request, previousFailure);
127 throw previousFailure;
131 return doHandleRequest(request, envelope, now);
132 } catch (RuntimeException e) {
134 * The request failed to process, we should not attempt to ever apply it again. Furthermore we cannot
135 * accept any further requests from this connection, simply because the transaction state is undefined.
137 LOG.debug("{}: Request {} failed to process", persistenceId(), request, e);
138 previousFailure = new RuntimeRequestException("Request " + request + " failed to process", e);
139 throw previousFailure;
143 abstract @Nullable TransactionSuccess<?> doHandleRequest(TransactionRequest<?> request, RequestEnvelope envelope,
144 long now) throws RequestException;
146 private void recordResponse(final long sequence, final Object response) {
147 if (replayQueue.isEmpty()) {
148 firstReplaySequence = sequence;
150 replayQueue.add(response);
154 final <T extends TransactionSuccess<?>> T recordSuccess(final long sequence, final T success) {
155 recordResponse(sequence, success);
159 private long executionTime(final long startTime) {
160 return history.readTime() - startTime;
163 final void recordAndSendSuccess(final RequestEnvelope envelope, final long startTime,
164 final TransactionSuccess<?> success) {
165 recordResponse(success.getSequence(), success);
166 envelope.sendSuccess(success, executionTime(startTime));
169 final void recordAndSendFailure(final RequestEnvelope envelope, final long startTime,
170 final RuntimeRequestException failure) {
171 recordResponse(envelope.getMessage().getSequence(), failure);
172 envelope.sendFailure(failure, executionTime(startTime));
176 public final String toString() {
177 return MoreObjects.toStringHelper(this).omitNullValues().add("identifier", getIdentifier())
178 .add("expectedSequence", expectedSequence).add("firstReplaySequence", firstReplaySequence)
179 .add("lastPurgedSequence", lastPurgedSequence)