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