Clean up unhandled request exceptions
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / databroker / actors / dds / AbstractProxyTransaction.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.databroker.actors.dds;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static com.google.common.base.Verify.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14
15 import akka.actor.ActorRef;
16 import com.google.common.base.MoreObjects;
17 import com.google.common.collect.Iterables;
18 import com.google.common.util.concurrent.FluentFuture;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.SettableFuture;
21 import java.util.ArrayDeque;
22 import java.util.Deque;
23 import java.util.Iterator;
24 import java.util.Optional;
25 import java.util.OptionalLong;
26 import java.util.concurrent.CountDownLatch;
27 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
28 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
29 import java.util.function.Consumer;
30 import org.checkerframework.checker.lock.qual.GuardedBy;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.opendaylight.controller.cluster.access.client.ConnectionEntry;
34 import org.opendaylight.controller.cluster.access.commands.AbstractLocalTransactionRequest;
35 import org.opendaylight.controller.cluster.access.commands.ClosedTransactionException;
36 import org.opendaylight.controller.cluster.access.commands.IncrementTransactionSequenceRequest;
37 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionRequest;
38 import org.opendaylight.controller.cluster.access.commands.TransactionAbortRequest;
39 import org.opendaylight.controller.cluster.access.commands.TransactionAbortSuccess;
40 import org.opendaylight.controller.cluster.access.commands.TransactionCanCommitSuccess;
41 import org.opendaylight.controller.cluster.access.commands.TransactionCommitSuccess;
42 import org.opendaylight.controller.cluster.access.commands.TransactionDoCommitRequest;
43 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitRequest;
44 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitSuccess;
45 import org.opendaylight.controller.cluster.access.commands.TransactionPurgeRequest;
46 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
47 import org.opendaylight.controller.cluster.access.concepts.Request;
48 import org.opendaylight.controller.cluster.access.concepts.RequestFailure;
49 import org.opendaylight.controller.cluster.access.concepts.Response;
50 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
51 import org.opendaylight.yangtools.concepts.Identifiable;
52 import org.opendaylight.yangtools.yang.common.Empty;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * Class translating transaction operations towards a particular backend shard.
60  *
61  * <p>
62  * This class is not safe to access from multiple application threads, as is usual for transactions. Internal state
63  * transitions coming from interactions with backend are expected to be thread-safe.
64  *
65  * <p>
66  * This class interacts with the queueing mechanism in ClientActorBehavior, hence once we arrive at a decision
67  * to use either a local or remote implementation, we are stuck with it. We can re-evaluate on the next transaction.
68  *
69  * @author Robert Varga
70  */
71 abstract class AbstractProxyTransaction implements Identifiable<TransactionIdentifier> {
72     /**
73      * Marker object used instead of read-type of requests, which are satisfied only once. This has a lower footprint
74      * and allows compressing multiple requests into a single entry. This class is not thread-safe.
75      */
76     private static final class IncrementSequence {
77         private final long sequence;
78         private long delta = 0;
79
80         IncrementSequence(final long sequence) {
81             this.sequence = sequence;
82         }
83
84         long getDelta() {
85             return delta;
86         }
87
88         long getSequence() {
89             return sequence;
90         }
91
92         void incrementDelta() {
93             delta++;
94         }
95     }
96
97     /**
98      * Base class for representing logical state of this proxy. See individual instantiations and {@link SuccessorState}
99      * for details.
100      */
101     private static class State {
102         private final String string;
103
104         State(final String string) {
105             this.string = requireNonNull(string);
106         }
107
108         @Override
109         public final String toString() {
110             return string;
111         }
112     }
113
114     /**
115      * State class used when a successor has interfered. Contains coordinator latch, the successor and previous state.
116      * This is a temporary state introduced during reconnection process and is necessary for correct state hand-off
117      * between the old connection (potentially being accessed by the user) and the new connection (being cleaned up
118      * by the actor.
119      *
120      * <p>
121      * When a user operation encounters this state, it synchronizes on the it and wait until reconnection completes,
122      * at which point the request is routed to the successor transaction. This is a relatively heavy-weight solution
123      * to the problem of state transfer, but the user will observe it only if the race condition is hit.
124      */
125     private static class SuccessorState extends State {
126         private final CountDownLatch latch = new CountDownLatch(1);
127         private AbstractProxyTransaction successor;
128         private State prevState;
129
130         // SUCCESSOR + DONE
131         private boolean done;
132
133         SuccessorState() {
134             super("SUCCESSOR");
135         }
136
137         // Synchronize with succession process and return the successor
138         AbstractProxyTransaction await() {
139             try {
140                 latch.await();
141             } catch (InterruptedException e) {
142                 LOG.warn("Interrupted while waiting for latch of {}", successor);
143                 throw new RuntimeException(e);
144             }
145             return successor;
146         }
147
148         void finish() {
149             latch.countDown();
150         }
151
152         State getPrevState() {
153             return verifyNotNull(prevState, "Attempted to access previous state, which was not set");
154         }
155
156         void setPrevState(final State prevState) {
157             verify(this.prevState == null, "Attempted to set previous state to %s when we already have %s", prevState,
158                     this.prevState);
159             this.prevState = requireNonNull(prevState);
160             // We cannot have duplicate successor states, so this check is sufficient
161             done = DONE.equals(prevState);
162         }
163
164         // To be called from safe contexts, where successor is known to be completed
165         AbstractProxyTransaction getSuccessor() {
166             return verifyNotNull(successor);
167         }
168
169         void setSuccessor(final AbstractProxyTransaction successor) {
170             verify(this.successor == null, "Attempted to set successor to %s when we already have %s", successor,
171                     this.successor);
172             this.successor = requireNonNull(successor);
173         }
174
175         boolean isDone() {
176             return done;
177         }
178
179         void setDone() {
180             done = true;
181         }
182     }
183
184     private static final Logger LOG = LoggerFactory.getLogger(AbstractProxyTransaction.class);
185     private static final AtomicIntegerFieldUpdater<AbstractProxyTransaction> SEALED_UPDATER =
186             AtomicIntegerFieldUpdater.newUpdater(AbstractProxyTransaction.class, "sealed");
187     private static final AtomicReferenceFieldUpdater<AbstractProxyTransaction, State> STATE_UPDATER =
188             AtomicReferenceFieldUpdater.newUpdater(AbstractProxyTransaction.class, State.class, "state");
189
190     /**
191      * Transaction has been open and is being actively worked on.
192      */
193     private static final State OPEN = new State("OPEN");
194
195     /**
196      * Transaction has been sealed by the user, but it has not completed flushing to the backed, yet. This is
197      * a transition state, as we are waiting for the user to initiate commit procedures.
198      *
199      * <p>
200      * Since the reconnect mechanics relies on state replay for transactions, this state needs to be flushed into the
201      * queue to re-create state in successor transaction (which may be based on different messages as locality may have
202      * changed). Hence the transition to {@link #FLUSHED} state needs to be handled in a thread-safe manner.
203      */
204     private static final State SEALED = new State("SEALED");
205
206     /**
207      * Transaction state has been flushed into the queue, i.e. it is visible by the successor and potentially
208      * the backend. At this point the transaction does not hold any state besides successful requests, all other state
209      * is held either in the connection's queue or the successor object.
210      *
211      * <p>
212      * Transition to this state indicates we have all input from the user we need to initiate the correct commit
213      * protocol.
214      */
215     private static final State FLUSHED = new State("FLUSHED");
216
217     /**
218      * Transaction state has been completely resolved, we have received confirmation of the transaction fate from
219      * the backend. The only remaining task left to do is finishing up the state cleanup, which is done via purge
220      * request. We need to hang on to the transaction until that is done, as we have to make sure backend completes
221      * purging its state -- otherwise we could have a leak on the backend.
222      */
223     private static final State DONE = new State("DONE");
224
225     // Touched from client actor thread only
226     private final Deque<Object> successfulRequests = new ArrayDeque<>();
227     private final ProxyHistory parent;
228
229     // Accessed from user thread only, which may not access this object concurrently
230     private long sequence;
231
232     /*
233      * Atomic state-keeping is required to synchronize the process of propagating completed transaction state towards
234      * the backend -- which may include a successor.
235      *
236      * Successor, unlike {@link AbstractProxyTransaction#seal()} is triggered from the client actor thread, which means
237      * the successor placement needs to be atomic with regard to the application thread.
238      *
239      * In the common case, the application thread performs performs the seal operations and then "immediately" sends
240      * the corresponding message. The uncommon case is when the seal and send operations race with a connect completion
241      * or timeout, when a successor is injected.
242      *
243      * This leaves the problem of needing to completely transferring state just after all queued messages are replayed
244      * after a successor was injected, so that it can be properly sealed if we are racing. Further complication comes
245      * from lock ordering, where the successor injection works with a locked queue and locks proxy objects -- leading
246      * to a potential AB-BA deadlock in case of a naive implementation.
247      *
248      * For tracking user-visible state we use a single volatile int, which is flipped atomically from 0 to 1 exactly
249      * once in {@link AbstractProxyTransaction#seal()}. That keeps common operations fast, as they need to perform
250      * only a single volatile read to assert state correctness.
251      *
252      * For synchronizing client actor (successor-injecting) and user (commit-driving) thread, we keep a separate state
253      * variable. It uses pre-allocated objects for fast paths (i.e. no successor present) and a per-transition object
254      * for slow paths (when successor is injected/present).
255      */
256     private volatile int sealed;
257     private volatile State state;
258
259     AbstractProxyTransaction(final ProxyHistory parent, final boolean isDone) {
260         this.parent = requireNonNull(parent);
261         if (isDone) {
262             state = DONE;
263             // DONE implies previous seal operation completed
264             sealed = 1;
265         } else {
266             state = OPEN;
267         }
268     }
269
270     final void executeInActor(final Runnable command) {
271         parent.context().executeInActor(behavior -> {
272             command.run();
273             return behavior;
274         });
275     }
276
277     final ActorRef localActor() {
278         return parent.localActor();
279     }
280
281     final void incrementSequence(final long delta) {
282         sequence += delta;
283         LOG.debug("Transaction {} incremented sequence to {}", this, sequence);
284     }
285
286     final long nextSequence() {
287         final long ret = sequence++;
288         LOG.debug("Transaction {} allocated sequence {}", this, ret);
289         return ret;
290     }
291
292     final void delete(final YangInstanceIdentifier path) {
293         checkReadWrite();
294         checkNotSealed();
295         doDelete(path);
296     }
297
298     final void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
299         checkReadWrite();
300         checkNotSealed();
301         doMerge(path, data);
302     }
303
304     final void write(final YangInstanceIdentifier path, final NormalizedNode data) {
305         checkReadWrite();
306         checkNotSealed();
307         doWrite(path, data);
308     }
309
310     final FluentFuture<Boolean> exists(final YangInstanceIdentifier path) {
311         checkNotSealed();
312         return doExists(path);
313     }
314
315     final FluentFuture<Optional<NormalizedNode>> read(final YangInstanceIdentifier path) {
316         checkNotSealed();
317         return doRead(path);
318     }
319
320     final void enqueueRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
321             final long enqueuedTicks) {
322         LOG.debug("Transaction proxy {} enqueing request {} callback {}", this, request, callback);
323         parent.enqueueRequest(request, callback, enqueuedTicks);
324     }
325
326     final void sendRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
327         LOG.debug("Transaction proxy {} sending request {} callback {}", this, request, callback);
328         parent.sendRequest(request, callback);
329     }
330
331     /**
332      * Seal this transaction before it is either committed or aborted. This method should only be invoked from
333      * application thread.
334      */
335     final void seal() {
336         // Transition user-visible state first
337         final boolean success = markSealed();
338         checkState(success, "Proxy %s was already sealed", getIdentifier());
339
340         if (!sealAndSend(OptionalLong.empty())) {
341             sealSuccessor();
342         }
343     }
344
345     /**
346      * Internal seal propagation method, invoked when we have raced with reconnection thread. Note that there may have
347      * been multiple reconnects, so we have to make sure the action is propagate through all intermediate instances.
348      */
349     private void sealSuccessor() {
350         // Slow path: wait for the successor to complete
351         final AbstractProxyTransaction successor = awaitSuccessor();
352
353         // At this point the successor has completed transition and is possibly visible by the user thread, which is
354         // still stuck here. The successor has not seen final part of our state, nor the fact it is sealed.
355         // Propagate state and seal the successor.
356         final Optional<ModifyTransactionRequest> optState = flushState();
357         if (optState.isPresent()) {
358             forwardToSuccessor(successor, optState.get(), null);
359         }
360         successor.predecessorSealed();
361     }
362
363     private void predecessorSealed() {
364         if (markSealed() && !sealAndSend(OptionalLong.empty())) {
365             sealSuccessor();
366         }
367     }
368
369     /**
370      * Seal this transaction. If this method reports false, the caller needs to deal with propagating the seal operation
371      * towards the successor.
372      *
373      * @return True if seal operation was successful, false if this proxy has a successor.
374      */
375     boolean sealOnly() {
376         return sealState();
377     }
378
379     /**
380      * Seal this transaction and potentially send it out towards the backend. If this method reports false, the caller
381      * needs to deal with propagating the seal operation towards the successor.
382      *
383      * @param enqueuedTicks Enqueue ticks when this is invoked from replay path.
384      * @return True if seal operation was successful, false if this proxy has a successor.
385      */
386     boolean sealAndSend(final OptionalLong enqueuedTicks) {
387         return sealState();
388     }
389
390     private boolean sealState() {
391         parent.onTransactionSealed(this);
392         // Transition internal state to sealed and detect presence of a successor
393         return STATE_UPDATER.compareAndSet(this, OPEN, SEALED);
394     }
395
396     /**
397      * Mark this proxy as having been sealed.
398      *
399      * @return True if this call has transitioned to sealed state.
400      */
401     final boolean markSealed() {
402         return SEALED_UPDATER.compareAndSet(this, 0, 1);
403     }
404
405     private void checkNotSealed() {
406         checkState(sealed == 0, "Transaction %s has already been sealed", getIdentifier());
407     }
408
409     private void checkSealed() {
410         checkState(sealed != 0, "Transaction %s has not been sealed yet", getIdentifier());
411     }
412
413     private SuccessorState getSuccessorState() {
414         final State local = state;
415         verify(local instanceof SuccessorState, "State %s has unexpected class", local);
416         return (SuccessorState) local;
417     }
418
419     private void checkReadWrite() {
420         if (isSnapshotOnly()) {
421             throw new UnsupportedOperationException("Transaction " + getIdentifier() + " is a read-only snapshot");
422         }
423     }
424
425     final void recordSuccessfulRequest(final @NonNull TransactionRequest<?> req) {
426         successfulRequests.add(verifyNotNull(req));
427     }
428
429     final void recordFinishedRequest(final Response<?, ?> response) {
430         final Object last = successfulRequests.peekLast();
431         if (last instanceof IncrementSequence) {
432             ((IncrementSequence) last).incrementDelta();
433         } else {
434             successfulRequests.addLast(new IncrementSequence(response.getSequence()));
435         }
436     }
437
438     /**
439      * Abort this transaction. This is invoked only for read-only transactions and will result in an explicit message
440      * being sent to the backend.
441      */
442     final void abort() {
443         checkNotSealed();
444         parent.abortTransaction(this);
445
446         sendRequest(abortRequest(), resp -> {
447             LOG.debug("Transaction {} abort completed with {}", getIdentifier(), resp);
448             enqueuePurge();
449         });
450     }
451
452     final void abort(final VotingFuture<Empty> ret) {
453         checkSealed();
454
455         sendDoAbort(t -> {
456             if (t instanceof TransactionAbortSuccess) {
457                 ret.voteYes();
458             } else if (t instanceof RequestFailure) {
459                 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
460             } else {
461                 ret.voteNo(unhandledResponseException(t));
462             }
463
464             // This is a terminal request, hence we do not need to record it
465             LOG.debug("Transaction {} abort completed", this);
466             enqueuePurge();
467         });
468     }
469
470     final void enqueueAbort(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
471         checkNotSealed();
472         parent.abortTransaction(this);
473
474         enqueueRequest(abortRequest(), resp -> {
475             LOG.debug("Transaction {} abort completed with {}", getIdentifier(), resp);
476             // Purge will be sent by the predecessor's callback
477             if (callback != null) {
478                 callback.accept(resp);
479             }
480         }, enqueuedTicks);
481     }
482
483     final void enqueueDoAbort(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
484         enqueueRequest(new TransactionAbortRequest(getIdentifier(), nextSequence(), localActor()), callback,
485             enqueuedTicks);
486     }
487
488     final void sendDoAbort(final Consumer<Response<?, ?>> callback) {
489         sendRequest(new TransactionAbortRequest(getIdentifier(), nextSequence(), localActor()), callback);
490     }
491
492     /**
493      * Commit this transaction, possibly in a coordinated fashion.
494      *
495      * @param coordinated True if this transaction should be coordinated across multiple participants.
496      * @return Future completion
497      */
498     final ListenableFuture<Boolean> directCommit() {
499         checkReadWrite();
500         checkSealed();
501
502         // Precludes startReconnect() from interfering with the fast path
503         synchronized (this) {
504             if (STATE_UPDATER.compareAndSet(this, SEALED, FLUSHED)) {
505                 final SettableFuture<Boolean> ret = SettableFuture.create();
506                 sendRequest(verifyNotNull(commitRequest(false)), t -> {
507                     if (t instanceof TransactionCommitSuccess) {
508                         ret.set(Boolean.TRUE);
509                     } else if (t instanceof RequestFailure) {
510                         final Throwable cause = ((RequestFailure<?, ?>) t).getCause().unwrap();
511                         if (cause instanceof ClosedTransactionException) {
512                             // This is okay, as it indicates the transaction has been completed. It can happen
513                             // when we lose connectivity with the backend after it has received the request.
514                             ret.set(Boolean.TRUE);
515                         } else {
516                             ret.setException(cause);
517                         }
518                     } else {
519                         ret.setException(unhandledResponseException(t));
520                     }
521
522                     // This is a terminal request, hence we do not need to record it
523                     LOG.debug("Transaction {} directCommit completed", this);
524                     enqueuePurge();
525                 });
526
527                 return ret;
528             }
529         }
530
531         // We have had some interference with successor injection, wait for it to complete and defer to the successor.
532         return awaitSuccessor().directCommit();
533     }
534
535     final void canCommit(final VotingFuture<?> ret) {
536         checkReadWrite();
537         checkSealed();
538
539         // Precludes startReconnect() from interfering with the fast path
540         synchronized (this) {
541             if (STATE_UPDATER.compareAndSet(this, SEALED, FLUSHED)) {
542                 final TransactionRequest<?> req = verifyNotNull(commitRequest(true));
543
544                 sendRequest(req, t -> {
545                     if (t instanceof TransactionCanCommitSuccess) {
546                         ret.voteYes();
547                     } else if (t instanceof RequestFailure) {
548                         ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
549                     } else {
550                         ret.voteNo(unhandledResponseException(t));
551                     }
552
553                     recordSuccessfulRequest(req);
554                     LOG.debug("Transaction {} canCommit completed", this);
555                 });
556
557                 return;
558             }
559         }
560
561         // We have had some interference with successor injection, wait for it to complete and defer to the successor.
562         awaitSuccessor().canCommit(ret);
563     }
564
565     private AbstractProxyTransaction awaitSuccessor() {
566         return getSuccessorState().await();
567     }
568
569     final void preCommit(final VotingFuture<?> ret) {
570         checkReadWrite();
571         checkSealed();
572
573         final TransactionRequest<?> req = new TransactionPreCommitRequest(getIdentifier(), nextSequence(),
574             localActor());
575         sendRequest(req, t -> {
576             if (t instanceof TransactionPreCommitSuccess) {
577                 ret.voteYes();
578             } else if (t instanceof RequestFailure) {
579                 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
580             } else {
581                 ret.voteNo(unhandledResponseException(t));
582             }
583
584             onPreCommitComplete(req);
585         });
586     }
587
588     private void onPreCommitComplete(final TransactionRequest<?> req) {
589         /*
590          * The backend has agreed that the transaction has entered PRE_COMMIT phase, meaning it will be committed
591          * to storage after the timeout completes.
592          *
593          * All state has been replicated to the backend, hence we do not need to keep it around. Retain only
594          * the precommit request, so we know which request to use for resync.
595          */
596         LOG.debug("Transaction {} preCommit completed, clearing successfulRequests", this);
597         successfulRequests.clear();
598
599         // TODO: this works, but can contain some useless state (like batched operations). Create an empty
600         //       equivalent of this request and store that.
601         recordSuccessfulRequest(req);
602     }
603
604     final void doCommit(final VotingFuture<?> ret) {
605         checkReadWrite();
606         checkSealed();
607
608         sendRequest(new TransactionDoCommitRequest(getIdentifier(), nextSequence(), localActor()), t -> {
609             if (t instanceof TransactionCommitSuccess) {
610                 ret.voteYes();
611             } else if (t instanceof RequestFailure) {
612                 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
613             } else {
614                 ret.voteNo(unhandledResponseException(t));
615             }
616
617             LOG.debug("Transaction {} doCommit completed", this);
618
619             // Needed for ProxyHistory$Local data tree rebase points.
620             parent.completeTransaction(this);
621
622             enqueuePurge();
623         });
624     }
625
626     private void enqueuePurge() {
627         enqueuePurge(null);
628     }
629
630     final void enqueuePurge(final Consumer<Response<?, ?>> callback) {
631         // Purge request are dispatched internally, hence should not wait
632         enqueuePurge(callback, parent.currentTime());
633     }
634
635     final void enqueuePurge(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
636         LOG.debug("{}: initiating purge", this);
637
638         final State prev = state;
639         if (prev instanceof SuccessorState) {
640             ((SuccessorState) prev).setDone();
641         } else {
642             final boolean success = STATE_UPDATER.compareAndSet(this, prev, DONE);
643             if (!success) {
644                 LOG.warn("{}: moved from state {} while we were purging it", this, prev);
645             }
646         }
647
648         successfulRequests.clear();
649
650         enqueueRequest(new TransactionPurgeRequest(getIdentifier(), nextSequence(), localActor()), resp -> {
651             LOG.debug("{}: purge completed", this);
652             parent.purgeTransaction(this);
653
654             if (callback != null) {
655                 callback.accept(resp);
656             }
657         }, enqueuedTicks);
658     }
659
660     // Called with the connection unlocked
661     final synchronized void startReconnect() {
662         // At this point canCommit/directCommit are blocked, we assert a new successor state, retrieving the previous
663         // state. This method is called with the queue still unlocked.
664         final SuccessorState nextState = new SuccessorState();
665         final State prevState = STATE_UPDATER.getAndSet(this, nextState);
666
667         LOG.debug("Start reconnect of proxy {} previous state {}", this, prevState);
668         verify(!(prevState instanceof SuccessorState), "Proxy %s duplicate reconnect attempt after %s", this,
669             prevState);
670
671         // We have asserted a slow-path state, seal(), canCommit(), directCommit() are forced to slow paths, which will
672         // wait until we unblock nextState's latch before accessing state. Now we record prevState for later use and we
673         // are done.
674         nextState.setPrevState(prevState);
675     }
676
677     // Called with the connection locked
678     final void replayMessages(final ProxyHistory successorHistory, final Iterable<ConnectionEntry> enqueuedEntries) {
679         final SuccessorState local = getSuccessorState();
680         final State prevState = local.getPrevState();
681
682         final AbstractProxyTransaction successor = successorHistory.createTransactionProxy(getIdentifier(),
683             isSnapshotOnly(), local.isDone());
684         LOG.debug("{} created successor {}", this, successor);
685         local.setSuccessor(successor);
686
687         // Replay successful requests first
688         if (!successfulRequests.isEmpty()) {
689             // We need to find a good timestamp to use for successful requests, as we do not want to time them out
690             // nor create timing inconsistencies in the queue -- requests are expected to be ordered by their enqueue
691             // time. We will pick the time of the first entry available. If there is none, we will just use current
692             // time, as all other requests will get enqueued afterwards.
693             final ConnectionEntry firstInQueue = Iterables.getFirst(enqueuedEntries, null);
694             final long now = firstInQueue != null ? firstInQueue.getEnqueuedTicks() : parent.currentTime();
695
696             for (Object obj : successfulRequests) {
697                 if (obj instanceof TransactionRequest) {
698                     LOG.debug("Forwarding successful request {} to successor {}", obj, successor);
699                     successor.doReplayRequest((TransactionRequest<?>) obj, resp -> { /*NOOP*/ }, now);
700                 } else {
701                     verify(obj instanceof IncrementSequence);
702                     final IncrementSequence increment = (IncrementSequence) obj;
703                     successor.doReplayRequest(new IncrementTransactionSequenceRequest(getIdentifier(),
704                         increment.getSequence(), localActor(), isSnapshotOnly(),
705                         increment.getDelta()), resp -> { /*NOOP*/ }, now);
706                     LOG.debug("Incrementing sequence {} to successor {}", obj, successor);
707                 }
708             }
709             LOG.debug("{} replayed {} successful requests", getIdentifier(), successfulRequests.size());
710             successfulRequests.clear();
711         }
712
713         // Now replay whatever is in the connection
714         final Iterator<ConnectionEntry> it = enqueuedEntries.iterator();
715         while (it.hasNext()) {
716             final ConnectionEntry e = it.next();
717             final Request<?, ?> req = e.getRequest();
718
719             if (getIdentifier().equals(req.getTarget())) {
720                 verify(req instanceof TransactionRequest, "Unhandled request %s", req);
721                 LOG.debug("Replaying queued request {} to successor {}", req, successor);
722                 successor.doReplayRequest((TransactionRequest<?>) req, e.getCallback(), e.getEnqueuedTicks());
723                 it.remove();
724             }
725         }
726
727         /*
728          * Check the state at which we have started the reconnect attempt. State transitions triggered while we were
729          * reconnecting have been forced to slow paths, which will be unlocked once we unblock the state latch
730          * at the end of this method.
731          */
732         if (SEALED.equals(prevState)) {
733             LOG.debug("Proxy {} reconnected while being sealed, propagating state to successor {}", this, successor);
734             final long enqueuedTicks = parent.currentTime();
735             final Optional<ModifyTransactionRequest> optState = flushState();
736             if (optState.isPresent()) {
737                 successor.handleReplayedRemoteRequest(optState.get(), null, enqueuedTicks);
738             }
739             if (successor.markSealed()) {
740                 successor.sealAndSend(OptionalLong.of(enqueuedTicks));
741             }
742         }
743     }
744
745     /**
746      * Invoked from {@link #replayMessages(AbstractProxyTransaction, Iterable)} to have successor adopt an in-flight
747      * request.
748      *
749      * <p>
750      * Note: this method is invoked by the predecessor on the successor.
751      *
752      * @param request Request which needs to be forwarded
753      * @param callback Callback to be invoked once the request completes
754      * @param enqueuedTicks ticker-based time stamp when the request was enqueued
755      */
756     private void doReplayRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
757             final long enqueuedTicks) {
758         if (request instanceof AbstractLocalTransactionRequest) {
759             handleReplayedLocalRequest((AbstractLocalTransactionRequest<?>) request, callback, enqueuedTicks);
760         } else {
761             handleReplayedRemoteRequest(request, callback, enqueuedTicks);
762         }
763     }
764
765     // Called with the connection locked
766     final void finishReconnect() {
767         final SuccessorState local = getSuccessorState();
768         LOG.debug("Finishing reconnect of proxy {}", this);
769
770         // All done, release the latch, unblocking seal() and canCommit() slow paths
771         local.finish();
772     }
773
774     /**
775      * Invoked from a retired connection for requests which have been in-flight and need to be re-adjusted
776      * and forwarded to the successor connection.
777      *
778      * @param request Request to be forwarded
779      * @param callback Original callback
780      */
781     final void forwardRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
782         forwardToSuccessor(getSuccessorState().getSuccessor(), request, callback);
783     }
784
785     final void forwardToSuccessor(final AbstractProxyTransaction successor, final TransactionRequest<?> request,
786             final Consumer<Response<?, ?>> callback) {
787         if (successor instanceof LocalProxyTransaction) {
788             forwardToLocal((LocalProxyTransaction)successor, request, callback);
789         } else if (successor instanceof RemoteProxyTransaction) {
790             forwardToRemote((RemoteProxyTransaction)successor, request, callback);
791         } else {
792             throw new IllegalStateException("Unhandled successor " + successor);
793         }
794     }
795
796     final void replayRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
797             final long enqueuedTicks) {
798         getSuccessorState().getSuccessor().doReplayRequest(request, callback, enqueuedTicks);
799     }
800
801     abstract boolean isSnapshotOnly();
802
803     abstract void doDelete(YangInstanceIdentifier path);
804
805     abstract void doMerge(YangInstanceIdentifier path, NormalizedNode data);
806
807     abstract void doWrite(YangInstanceIdentifier path, NormalizedNode data);
808
809     abstract FluentFuture<Boolean> doExists(YangInstanceIdentifier path);
810
811     abstract FluentFuture<Optional<NormalizedNode>> doRead(YangInstanceIdentifier path);
812
813     @GuardedBy("this")
814     abstract Optional<ModifyTransactionRequest> flushState();
815
816     abstract TransactionRequest<?> abortRequest();
817
818     abstract TransactionRequest<?> commitRequest(boolean coordinated);
819
820     /**
821      * Replay a request originating in this proxy to a successor remote proxy.
822      */
823     abstract void forwardToRemote(RemoteProxyTransaction successor, TransactionRequest<?> request,
824             Consumer<Response<?, ?>> callback);
825
826     /**
827      * Replay a request originating in this proxy to a successor local proxy.
828      */
829     abstract void forwardToLocal(LocalProxyTransaction successor, TransactionRequest<?> request,
830             Consumer<Response<?, ?>> callback);
831
832     /**
833      * Invoked from {@link LocalProxyTransaction} when it replays its successful requests to its successor.
834      *
835      * <p>
836      * Note: this method is invoked by the predecessor on the successor.
837      *
838      * @param request Request which needs to be forwarded
839      * @param callback Callback to be invoked once the request completes
840      * @param enqueuedTicks Time stamp to use for enqueue time
841      */
842     abstract void handleReplayedLocalRequest(AbstractLocalTransactionRequest<?> request,
843             @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
844
845     /**
846      * Invoked from {@link RemoteProxyTransaction} when it replays its successful requests to its successor.
847      *
848      * <p>
849      * Note: this method is invoked by the predecessor on the successor.
850      *
851      * @param request Request which needs to be forwarded
852      * @param callback Callback to be invoked once the request completes
853      * @param enqueuedTicks Time stamp to use for enqueue time
854      */
855     abstract void handleReplayedRemoteRequest(TransactionRequest<?> request,
856             @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
857
858     static final @NonNull IllegalArgumentException unhandledRequest(final TransactionRequest<?> request) {
859         return new IllegalArgumentException("Unhandled request " + request);
860     }
861
862     private static @NonNull IllegalStateException unhandledResponseException(final Response<?, ?> resp) {
863         return new IllegalStateException("Unhandled response " + resp.getClass());
864     }
865
866     @Override
867     public final String toString() {
868         return MoreObjects.toStringHelper(this).add("identifier", getIdentifier()).add("state", state).toString();
869     }
870 }