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