BUG-8402: Record modification failures
[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 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 /**
30  * Frontend common transaction state as observed by the shard leader.
31  *
32  * @author Robert Varga
33  */
34 @NotThreadSafe
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 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();
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         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;
102                 }
103
104                 Verify.verify(replay instanceof TransactionSuccess);
105                 return java.util.Optional.of((TransactionSuccess<?>) replay);
106             }
107
108             replaySequence++;
109         }
110
111         // Not found
112         return java.util.Optional.empty();
113     }
114
115     final void purgeSequencesUpTo(final long sequence) {
116         // FIXME: implement this
117
118         lastPurgedSequence = sequence;
119     }
120
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;
128         }
129
130         try {
131             return doHandleRequest(request, envelope, now);
132         } catch (RuntimeException e) {
133             /*
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.
136              */
137             LOG.debug("{}: Request {} failed to process", persistenceId(), request, e);
138             previousFailure = new RuntimeRequestException("Request " + request + " failed to process", e);
139             throw previousFailure;
140         }
141     }
142
143     abstract @Nullable TransactionSuccess<?> doHandleRequest(TransactionRequest<?> request, RequestEnvelope envelope,
144             long now) throws RequestException;
145
146     private void recordResponse(final long sequence, final Object response) {
147         if (replayQueue.isEmpty()) {
148             firstReplaySequence = sequence;
149         }
150         replayQueue.add(response);
151         expectedSequence++;
152     }
153
154     final <T extends TransactionSuccess<?>> T recordSuccess(final long sequence, final T success) {
155         recordResponse(sequence, success);
156         return success;
157     }
158
159     private long executionTime(final long startTime) {
160         return history.readTime() - startTime;
161     }
162
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));
167     }
168
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));
173     }
174
175     @Override
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)
180                 .toString();
181     }
182
183 }