Move byte-based serialization method
[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 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;
29
30 /**
31  * Frontend common transaction state as observed by the shard leader. This class is NOT thread-safe.
32  *
33  * @author Robert Varga
34  */
35 abstract class FrontendTransaction implements Identifiable<TransactionIdentifier> {
36     private static final Logger LOG = LoggerFactory.getLogger(FrontendTransaction.class);
37
38     private final AbstractFrontendHistory history;
39     private final TransactionIdentifier id;
40
41     /**
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.
45      */
46     private final Queue<Object> replayQueue = new ArrayDeque<>();
47     private long firstReplaySequence;
48     private Long lastPurgedSequence;
49     private long expectedSequence;
50
51     private RequestException previousFailure;
52
53     FrontendTransaction(final AbstractFrontendHistory history, final TransactionIdentifier id) {
54         this.history = Preconditions.checkNotNull(history);
55         this.id = Preconditions.checkNotNull(id);
56     }
57
58     @Override
59     public final TransactionIdentifier getIdentifier() {
60         return id;
61     }
62
63     final AbstractFrontendHistory history() {
64         return history;
65     }
66
67     final String persistenceId() {
68         return history().persistenceId();
69     }
70
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();
75         }
76
77         // Check sequencing: we do not need to bother with future requests
78         if (Long.compareUnsigned(expectedSequence, sequence) < 0) {
79             throw new OutOfOrderRequestException(expectedSequence);
80         }
81
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));
89         }
90
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.
94
95         long replaySequence = firstReplaySequence;
96         for (Object replay : replayQueue) {
97             if (replaySequence == sequence) {
98                 if (replay instanceof RequestException) {
99                     throw (RequestException) replay;
100                 }
101
102                 Verify.verify(replay instanceof TransactionSuccess);
103                 return Optional.of((TransactionSuccess<?>) replay);
104             }
105
106             replaySequence++;
107         }
108
109         // Not found
110         return Optional.empty();
111     }
112
113     final void purgeSequencesUpTo(final long sequence) {
114         // FIXME: implement this
115
116         lastPurgedSequence = sequence;
117     }
118
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();
126
127             return recordSuccess(incr.getSequence(),
128                     new IncrementTransactionSequenceSuccess(incr.getTarget(), incr.getSequence()));
129         }
130
131         if (previousFailure != null) {
132             LOG.debug("{}: Rejecting request {} due to previous failure", persistenceId(), request, previousFailure);
133             throw previousFailure;
134         }
135
136         try {
137             return doHandleRequest(request, envelope, now);
138         } catch (RuntimeException e) {
139             /*
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
143              * undefined.
144              */
145             LOG.debug("{}: Request {} failed to process", persistenceId(), request, e);
146             previousFailure = new RuntimeRequestException("Request " + request + " failed to process", e);
147             throw previousFailure;
148         }
149     }
150
151     abstract @Nullable TransactionSuccess<?> doHandleRequest(TransactionRequest<?> request, RequestEnvelope envelope,
152             long now) throws RequestException;
153
154     abstract void retire();
155
156     private void recordResponse(final long sequence, final Object response) {
157         if (replayQueue.isEmpty()) {
158             firstReplaySequence = sequence;
159         }
160         replayQueue.add(response);
161         expectedSequence++;
162     }
163
164     final <T extends TransactionSuccess<?>> T recordSuccess(final long sequence, final T success) {
165         recordResponse(sequence, success);
166         return success;
167     }
168
169     private long executionTime(final long startTime) {
170         return history.readTime() - startTime;
171     }
172
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));
177     }
178
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));
183     }
184
185     @Override
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)
190                 .toString();
191     }
192 }