BUG 2138 - Do not fail on module-based default shard
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / FrontendTransaction.java
1 /*
2  * Copyright (c) 2016 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.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
27 /**
28  * Frontend common transaction state as observed by the shard leader.
29  *
30  * @author Robert Varga
31  */
32 @NotThreadSafe
33 abstract class FrontendTransaction implements Identifiable<TransactionIdentifier> {
34     private final AbstractFrontendHistory history;
35     private final TransactionIdentifier id;
36
37     /**
38      * It is possible that after we process a request and send a response that response gets lost and the client
39      * initiates a retry. Since subsequent requests can mutate transaction state we need to retain the response until
40      * it is acknowledged by the client.
41      */
42     private final Queue<Object> replayQueue = new ArrayDeque<>();
43     private long firstReplaySequence;
44     private Long lastPurgedSequence;
45     private long expectedSequence;
46
47     FrontendTransaction(final AbstractFrontendHistory history, final TransactionIdentifier id) {
48         this.history = Preconditions.checkNotNull(history);
49         this.id = Preconditions.checkNotNull(id);
50     }
51
52     @Override
53     public final TransactionIdentifier getIdentifier() {
54         return id;
55     }
56
57     final AbstractFrontendHistory history() {
58         return history;
59     }
60
61     final java.util.Optional<TransactionSuccess<?>> replaySequence(final long sequence) throws RequestException {
62         // Fast path check: if the requested sequence is the next request, bail early
63         if (expectedSequence == sequence) {
64             return java.util.Optional.empty();
65         }
66
67         // Check sequencing: we do not need to bother with future requests
68         if (Long.compareUnsigned(expectedSequence, sequence) < 0) {
69             throw new OutOfOrderRequestException(expectedSequence);
70         }
71
72         // Sanity check: if we have purged sequences, this has to be newer
73         if (lastPurgedSequence != null && Long.compareUnsigned(lastPurgedSequence.longValue(), sequence) >= 0) {
74             // Client has sent a request sequence, which has already been purged. This is a hard error, which should
75             // never occur. Throwing an IllegalArgumentException will cause it to be wrapped in a
76             // RuntimeRequestException (which is not retriable) and report it back to the client.
77             throw new IllegalArgumentException(String.format("Invalid purged sequence %s (last purged is %s)",
78                 sequence, lastPurgedSequence));
79         }
80
81         // At this point we have established that the requested sequence lies in the open interval
82         // (lastPurgedSequence, expectedSequence). That does not actually mean we have a response, as the commit
83         // machinery is asynchronous, hence a reply may be in the works and not available.
84
85         long replaySequence = firstReplaySequence;
86         final Iterator<?> it = replayQueue.iterator();
87         while (it.hasNext()) {
88             final Object replay = it.next();
89             if (replaySequence == sequence) {
90                 if (replay instanceof RequestException) {
91                     throw (RequestException) replay;
92                 }
93
94                 Verify.verify(replay instanceof TransactionSuccess);
95                 return java.util.Optional.of((TransactionSuccess<?>) replay);
96             }
97
98             replaySequence++;
99         }
100
101         // Not found
102         return java.util.Optional.empty();
103     }
104
105     final void purgeSequencesUpTo(final long sequence) {
106         // FIXME: implement this
107
108         lastPurgedSequence = sequence;
109     }
110
111     // Sequence has already been checked
112     abstract @Nullable TransactionSuccess<?> handleRequest(TransactionRequest<?> request,
113             RequestEnvelope envelope, long now) throws RequestException;
114
115     private void recordResponse(final long sequence, final Object response) {
116         if (replayQueue.isEmpty()) {
117             firstReplaySequence = sequence;
118         }
119         replayQueue.add(response);
120         expectedSequence++;
121     }
122
123     final <T extends TransactionSuccess<?>> T recordSuccess(final long sequence, final T success) {
124         recordResponse(sequence, success);
125         return success;
126     }
127
128     private long executionTime(final long startTime) {
129         return history.readTime() - startTime;
130     }
131
132     final void recordAndSendSuccess(final RequestEnvelope envelope, final long startTime,
133             final TransactionSuccess<?> success) {
134         recordResponse(success.getSequence(), success);
135         envelope.sendSuccess(success, executionTime(startTime));
136     }
137
138     final void recordAndSendFailure(final RequestEnvelope envelope, final long startTime,
139             final RuntimeRequestException failure) {
140         recordResponse(envelope.getMessage().getSequence(), failure);
141         envelope.sendFailure(failure, executionTime(startTime));
142     }
143
144     @Override
145     public final String toString() {
146         return MoreObjects.toStringHelper(this).omitNullValues().add("identifier", getIdentifier())
147                 .add("expectedSequence", expectedSequence).add("firstReplaySequence", firstReplaySequence)
148                 .add("lastPurgedSequence", lastPurgedSequence)
149                 .toString();
150     }
151
152 }