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