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