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