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