BUG-5280: implement backend message handling
[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.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Verify;
13 import com.google.common.primitives.UnsignedLong;
14 import com.google.common.util.concurrent.FutureCallback;
15 import java.util.ArrayDeque;
16 import java.util.Iterator;
17 import java.util.Queue;
18 import javax.annotation.Nullable;
19 import javax.annotation.concurrent.NotThreadSafe;
20 import org.opendaylight.controller.cluster.access.commands.CommitLocalTransactionRequest;
21 import org.opendaylight.controller.cluster.access.commands.ExistsTransactionRequest;
22 import org.opendaylight.controller.cluster.access.commands.ExistsTransactionSuccess;
23 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionRequest;
24 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionSuccess;
25 import org.opendaylight.controller.cluster.access.commands.OutOfOrderRequestException;
26 import org.opendaylight.controller.cluster.access.commands.PersistenceProtocol;
27 import org.opendaylight.controller.cluster.access.commands.ReadTransactionRequest;
28 import org.opendaylight.controller.cluster.access.commands.ReadTransactionSuccess;
29 import org.opendaylight.controller.cluster.access.commands.TransactionAbortRequest;
30 import org.opendaylight.controller.cluster.access.commands.TransactionAbortSuccess;
31 import org.opendaylight.controller.cluster.access.commands.TransactionCanCommitSuccess;
32 import org.opendaylight.controller.cluster.access.commands.TransactionCommitSuccess;
33 import org.opendaylight.controller.cluster.access.commands.TransactionDelete;
34 import org.opendaylight.controller.cluster.access.commands.TransactionDoCommitRequest;
35 import org.opendaylight.controller.cluster.access.commands.TransactionMerge;
36 import org.opendaylight.controller.cluster.access.commands.TransactionModification;
37 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitRequest;
38 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitSuccess;
39 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
40 import org.opendaylight.controller.cluster.access.commands.TransactionSuccess;
41 import org.opendaylight.controller.cluster.access.commands.TransactionWrite;
42 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
43 import org.opendaylight.controller.cluster.access.concepts.RequestException;
44 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
45 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
46 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
49 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * Frontend transaction state as observed by the shard leader.
55  *
56  * @author Robert Varga
57  */
58 @NotThreadSafe
59 final class FrontendTransaction {
60     private static final Logger LOG = LoggerFactory.getLogger(FrontendTransaction.class);
61
62     private final AbstractFrontendHistory history;
63     private final TransactionIdentifier id;
64
65     /**
66      * It is possible that after we process a request and send a response that response gets lost and the client
67      * initiates a retry. Since subsequent requests can mutate transaction state we need to retain the response until
68      * it is acknowledged by the client.
69      */
70     private final Queue<Object> replayQueue = new ArrayDeque<>();
71     private long firstReplaySequence;
72     private Long lastPurgedSequence;
73     private long expectedSequence;
74
75     private ReadWriteShardDataTreeTransaction openTransaction;
76     private ModifyTransactionSuccess cachedModifySuccess;
77     private DataTreeModification sealedModification;
78     private ShardDataTreeCohort readyCohort;
79
80     private FrontendTransaction(final AbstractFrontendHistory history, final TransactionIdentifier id,
81             final ReadWriteShardDataTreeTransaction transaction) {
82         this.history = Preconditions.checkNotNull(history);
83         this.id = Preconditions.checkNotNull(id);
84         this.openTransaction = Preconditions.checkNotNull(transaction);
85     }
86
87     private FrontendTransaction(final AbstractFrontendHistory history, final TransactionIdentifier id,
88             final DataTreeModification mod) {
89         this.history = Preconditions.checkNotNull(history);
90         this.id = Preconditions.checkNotNull(id);
91         this.sealedModification = Preconditions.checkNotNull(mod);
92     }
93
94     static FrontendTransaction createOpen(final AbstractFrontendHistory history,
95             final ReadWriteShardDataTreeTransaction transaction) {
96         return new FrontendTransaction(history, transaction.getIdentifier(), transaction);
97     }
98
99     static FrontendTransaction createReady(final AbstractFrontendHistory history, final TransactionIdentifier id,
100             final DataTreeModification mod) {
101         return new FrontendTransaction(history, id, mod);
102     }
103
104     java.util.Optional<TransactionSuccess<?>> replaySequence(final long sequence) throws RequestException {
105         // Fast path check: if the requested sequence is the next request, bail early
106         if (expectedSequence == sequence) {
107             return java.util.Optional.empty();
108         }
109
110         // Check sequencing: we do not need to bother with future requests
111         if (Long.compareUnsigned(expectedSequence, sequence) < 0) {
112             throw new OutOfOrderRequestException(expectedSequence);
113         }
114
115         // Sanity check: if we have purged sequences, this has to be newer
116         if (lastPurgedSequence != null && Long.compareUnsigned(lastPurgedSequence.longValue(), sequence) >= 0) {
117             // Client has sent a request sequence, which has already been purged. This is a hard error, which should
118             // never occur. Throwing an IllegalArgumentException will cause it to be wrapped in a
119             // RuntimeRequestException (which is not retriable) and report it back to the client.
120             throw new IllegalArgumentException(String.format("Invalid purged sequence %s (last purged is %s)",
121                 sequence, lastPurgedSequence));
122         }
123
124         // At this point we have established that the requested sequence lies in the open interval
125         // (lastPurgedSequence, expectedSequence). That does not actually mean we have a response, as the commit
126         // machinery is asynchronous, hence a reply may be in the works and not available.
127
128         long replaySequence = firstReplaySequence;
129         final Iterator<?> it = replayQueue.iterator();
130         while (it.hasNext()) {
131             final Object replay = it.next();
132             if (replaySequence == sequence) {
133                 if (replay instanceof RequestException) {
134                     throw (RequestException) replay;
135                 }
136
137                 Verify.verify(replay instanceof TransactionSuccess);
138                 return java.util.Optional.of((TransactionSuccess<?>) replay);
139             }
140
141             replaySequence++;
142         }
143
144         // Not found
145         return java.util.Optional.empty();
146     }
147
148     void purgeSequencesUpTo(final long sequence) {
149         // FIXME: implement this
150
151         lastPurgedSequence = sequence;
152     }
153
154     // Sequence has already been checked
155     @Nullable TransactionSuccess<?> handleRequest(final TransactionRequest<?> request, final RequestEnvelope envelope)
156             throws RequestException {
157         if (request instanceof ModifyTransactionRequest) {
158             return handleModifyTransaction((ModifyTransactionRequest) request, envelope);
159         } else if (request instanceof CommitLocalTransactionRequest) {
160             handleCommitLocalTransaction((CommitLocalTransactionRequest) request, envelope);
161             return null;
162         } else if (request instanceof ExistsTransactionRequest) {
163             return handleExistsTransaction((ExistsTransactionRequest) request);
164         } else if (request instanceof ReadTransactionRequest) {
165             return handleReadTransaction((ReadTransactionRequest) request);
166         } else if (request instanceof TransactionPreCommitRequest) {
167             handleTransactionPreCommit((TransactionPreCommitRequest) request, envelope);
168             return null;
169         } else if (request instanceof TransactionDoCommitRequest) {
170             handleTransactionDoCommit((TransactionDoCommitRequest) request, envelope);
171             return null;
172         } else if (request instanceof TransactionAbortRequest) {
173             handleTransactionAbort((TransactionAbortRequest) request, envelope);
174             return null;
175         } else {
176             throw new UnsupportedRequestException(request);
177         }
178     }
179
180     private void recordResponse(final long sequence, final Object response) {
181         if (replayQueue.isEmpty()) {
182             firstReplaySequence = sequence;
183         }
184         replayQueue.add(response);
185         expectedSequence++;
186     }
187
188     private <T extends TransactionSuccess<?>> T recordSuccess(final long sequence, final T success) {
189         recordResponse(sequence, success);
190         return success;
191     }
192
193     private void recordAndSendSuccess(final RequestEnvelope envelope, final TransactionSuccess<?> success) {
194         recordResponse(success.getSequence(), success);
195         envelope.sendSuccess(success);
196     }
197
198     private void recordAndSendFailure(final RequestEnvelope envelope, final RuntimeRequestException failure) {
199         recordResponse(envelope.getMessage().getSequence(), failure);
200         envelope.sendFailure(failure);
201     }
202
203     private void handleTransactionPreCommit(final TransactionPreCommitRequest request,
204             final RequestEnvelope envelope) throws RequestException {
205         readyCohort.preCommit(new FutureCallback<DataTreeCandidate>() {
206             @Override
207             public void onSuccess(final DataTreeCandidate result) {
208                 recordAndSendSuccess(envelope, new TransactionPreCommitSuccess(readyCohort.getIdentifier(),
209                     request.getSequence()));
210             }
211
212             @Override
213             public void onFailure(final Throwable failure) {
214                 recordAndSendFailure(envelope, new RuntimeRequestException("Precommit failed", failure));
215                 readyCohort = null;
216             }
217         });
218     }
219
220     private void handleTransactionDoCommit(final TransactionDoCommitRequest request, final RequestEnvelope envelope)
221             throws RequestException {
222         readyCohort.commit(new FutureCallback<UnsignedLong>() {
223             @Override
224             public void onSuccess(final UnsignedLong result) {
225                 successfulCommit(envelope);
226             }
227
228             @Override
229             public void onFailure(final Throwable failure) {
230                 recordAndSendFailure(envelope, new RuntimeRequestException("Commit failed", failure));
231                 readyCohort = null;
232             }
233         });
234     }
235
236     private void handleTransactionAbort(final TransactionAbortRequest request, final RequestEnvelope envelope)
237             throws RequestException {
238         readyCohort.abort(new FutureCallback<Void>() {
239             @Override
240             public void onSuccess(final Void result) {
241                 readyCohort = null;
242                 recordAndSendSuccess(envelope, new TransactionAbortSuccess(id, request.getSequence()));
243                 LOG.debug("Transaction {} aborted", id);
244             }
245
246             @Override
247             public void onFailure(final Throwable failure) {
248                 readyCohort = null;
249                 LOG.warn("Transaction {} abort failed", id, failure);
250                 recordAndSendFailure(envelope, new RuntimeRequestException("Abort failed", failure));
251             }
252         });
253     }
254
255     private void coordinatedCommit(final RequestEnvelope envelope) {
256         readyCohort.canCommit(new FutureCallback<Void>() {
257             @Override
258             public void onSuccess(final Void result) {
259                 recordAndSendSuccess(envelope, new TransactionCanCommitSuccess(readyCohort.getIdentifier(),
260                     envelope.getMessage().getSequence()));
261             }
262
263             @Override
264             public void onFailure(final Throwable failure) {
265                 recordAndSendFailure(envelope, new RuntimeRequestException("CanCommit failed", failure));
266                 readyCohort = null;
267             }
268         });
269     }
270
271     private void directCommit(final RequestEnvelope envelope) {
272         readyCohort.canCommit(new FutureCallback<Void>() {
273             @Override
274             public void onSuccess(final Void result) {
275                 successfulDirectCanCommit(envelope);
276             }
277
278             @Override
279             public void onFailure(final Throwable failure) {
280                 recordAndSendFailure(envelope, new RuntimeRequestException("CanCommit failed", failure));
281                 readyCohort = null;
282             }
283         });
284
285     }
286
287     private void successfulDirectCanCommit(final RequestEnvelope envelope) {
288         readyCohort.preCommit(new FutureCallback<DataTreeCandidate>() {
289             @Override
290             public void onSuccess(final DataTreeCandidate result) {
291                 successfulDirectPreCommit(envelope);
292             }
293
294             @Override
295             public void onFailure(final Throwable failure) {
296                 recordAndSendFailure(envelope, new RuntimeRequestException("PreCommit failed", failure));
297                 readyCohort = null;
298             }
299         });
300     }
301
302     private void successfulDirectPreCommit(final RequestEnvelope envelope) {
303         readyCohort.commit(new FutureCallback<UnsignedLong>() {
304
305             @Override
306             public void onSuccess(final UnsignedLong result) {
307                 successfulCommit(envelope);
308             }
309
310             @Override
311             public void onFailure(final Throwable failure) {
312                 recordAndSendFailure(envelope, new RuntimeRequestException("DoCommit failed", failure));
313                 readyCohort = null;
314             }
315         });
316     }
317
318     private void successfulCommit(final RequestEnvelope envelope) {
319         recordAndSendSuccess(envelope, new TransactionCommitSuccess(readyCohort.getIdentifier(),
320             envelope.getMessage().getSequence()));
321         readyCohort = null;
322     }
323
324     private void handleCommitLocalTransaction(final CommitLocalTransactionRequest request,
325             final RequestEnvelope envelope) throws RequestException {
326         if (sealedModification.equals(request.getModification())) {
327             readyCohort = history.createReadyCohort(id, sealedModification);
328
329             if (request.isCoordinated()) {
330                 coordinatedCommit(envelope);
331             } else {
332                 directCommit(envelope);
333             }
334         } else {
335             throw new UnsupportedRequestException(request);
336         }
337     }
338
339     private ExistsTransactionSuccess handleExistsTransaction(final ExistsTransactionRequest request)
340             throws RequestException {
341         final Optional<NormalizedNode<?, ?>> data = openTransaction.getSnapshot().readNode(request.getPath());
342         return recordSuccess(request.getSequence(), new ExistsTransactionSuccess(id, request.getSequence(),
343             data.isPresent()));
344     }
345
346     private ReadTransactionSuccess handleReadTransaction(final ReadTransactionRequest request) throws RequestException {
347         final Optional<NormalizedNode<?, ?>> data = openTransaction.getSnapshot().readNode(request.getPath());
348         return recordSuccess(request.getSequence(), new ReadTransactionSuccess(id, request.getSequence(), data));
349     }
350
351     private ModifyTransactionSuccess replyModifySuccess(final long sequence) {
352         if (cachedModifySuccess == null) {
353             cachedModifySuccess = new ModifyTransactionSuccess(id, sequence);
354         }
355
356         return recordSuccess(sequence, cachedModifySuccess);
357     }
358
359     private @Nullable TransactionSuccess<?> handleModifyTransaction(final ModifyTransactionRequest request,
360             final RequestEnvelope envelope) throws RequestException {
361
362         final DataTreeModification modification = openTransaction.getSnapshot();
363         for (TransactionModification m : request.getModifications()) {
364             if (m instanceof TransactionDelete) {
365                 modification.delete(m.getPath());
366             } else if (m instanceof TransactionWrite) {
367                 modification.write(m.getPath(), ((TransactionWrite) m).getData());
368             } else if (m instanceof TransactionMerge) {
369                 modification.merge(m.getPath(), ((TransactionMerge) m).getData());
370             } else {
371                 LOG.warn("{}: ignoring unhandled modification {}", history.persistenceId(), m);
372             }
373         }
374
375         final java.util.Optional<PersistenceProtocol> maybeProto = request.getPersistenceProtocol();
376         if (!maybeProto.isPresent()) {
377             return replyModifySuccess(request.getSequence());
378         }
379
380         switch (maybeProto.get()) {
381             case ABORT:
382                 openTransaction.abort();
383                 openTransaction = null;
384                 return replyModifySuccess(request.getSequence());
385             case SIMPLE:
386                 readyCohort = openTransaction.ready();
387                 openTransaction = null;
388                 directCommit(envelope);
389                 return null;
390             case THREE_PHASE:
391                 readyCohort = openTransaction.ready();
392                 openTransaction = null;
393                 coordinatedCommit(envelope);
394                 return null;
395             default:
396                 throw new UnsupportedRequestException(request);
397         }
398     }
399 }