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