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