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