51f528150d22a717034cc4281618591645cca92f
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / databroker / actors / dds / AbstractProxyTransaction.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.databroker.actors.dds;
9
10 import akka.actor.ActorRef;
11 import com.google.common.base.MoreObjects;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Verify;
15 import com.google.common.collect.Iterables;
16 import com.google.common.util.concurrent.CheckedFuture;
17 import com.google.common.util.concurrent.ListenableFuture;
18 import com.google.common.util.concurrent.SettableFuture;
19 import java.util.ArrayDeque;
20 import java.util.Deque;
21 import java.util.Iterator;
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.mdsal.common.api.ReadFailedException;
49 import org.opendaylight.yangtools.concepts.Identifiable;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * Class translating transaction operations towards a particular backend shard.
57  *
58  * <p>
59  * This class is not safe to access from multiple application threads, as is usual for transactions. Internal state
60  * transitions coming from interactions with backend are expected to be thread-safe.
61  *
62  * <p>
63  * This class interacts with the queueing mechanism in ClientActorBehavior, hence once we arrive at a decision
64  * to use either a local or remote implementation, we are stuck with it. We can re-evaluate on the next transaction.
65  *
66  * @author Robert Varga
67  */
68 abstract class AbstractProxyTransaction implements Identifiable<TransactionIdentifier> {
69     /**
70      * Marker object used instead of read-type of requests, which are satisfied only once. This has a lower footprint
71      * and allows compressing multiple requests into a single entry.
72      */
73     @NotThreadSafe
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 = Preconditions.checkNotNull(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 Verify.verifyNotNull(prevState, "Attempted to access previous state, which was not set");
152         }
153
154         void setPrevState(final State prevState) {
155             Verify.verify(this.prevState == null, "Attempted to set previous state to %s when we already have %s",
156                     prevState, this.prevState);
157             this.prevState = Preconditions.checkNotNull(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 Verify.verifyNotNull(successor);
165         }
166
167         void setSuccessor(final AbstractProxyTransaction successor) {
168             Verify.verify(this.successor == null, "Attempted to set successor to %s when we already have %s",
169                     successor, this.successor);
170             this.successor = Preconditions.checkNotNull(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 = Preconditions.checkNotNull(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 CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
309         checkNotSealed();
310         return doExists(path);
311     }
312
313     final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> 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         Preconditions.checkState(success, "Proxy %s was already sealed", getIdentifier());
337
338         if (!sealAndSend(Optional.absent())) {
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 java.util.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.absent())) {
363             sealSuccessor();
364         }
365     }
366
367     void sealOnly() {
368         parent.onTransactionSealed(this);
369         final boolean success = STATE_UPDATER.compareAndSet(this, OPEN, SEALED);
370         Verify.verify(success, "Attempted to replay seal on %s", this);
371     }
372
373     /**
374      * Seal this transaction and potentially send it out towards the backend. If this method reports false, the caller
375      * needs to deal with propagating the seal operation towards the successor.
376      *
377      * @param enqueuedTicks Enqueue ticks when this is invoked from replay path.
378      * @return True if seal operation was successful, false if this proxy has a successor.
379      */
380     boolean sealAndSend(final Optional<Long> enqueuedTicks) {
381         parent.onTransactionSealed(this);
382
383         // Transition internal state to sealed and detect presence of a successor
384         return STATE_UPDATER.compareAndSet(this, OPEN, SEALED);
385     }
386
387     /**
388      * Mark this proxy as having been sealed.
389      *
390      * @return True if this call has transitioned to sealed state.
391      */
392     final boolean markSealed() {
393         return SEALED_UPDATER.compareAndSet(this, 0, 1);
394     }
395
396     private void checkNotSealed() {
397         Preconditions.checkState(sealed == 0, "Transaction %s has already been sealed", getIdentifier());
398     }
399
400     private void checkSealed() {
401         Preconditions.checkState(sealed != 0, "Transaction %s has not been sealed yet", getIdentifier());
402     }
403
404     private SuccessorState getSuccessorState() {
405         final State local = state;
406         Verify.verify(local instanceof SuccessorState, "State %s has unexpected class", local);
407         return (SuccessorState) local;
408     }
409
410     private void checkReadWrite() {
411         if (isSnapshotOnly()) {
412             throw new UnsupportedOperationException("Transaction " + getIdentifier() + " is a read-only snapshot");
413         }
414     }
415
416     final void recordSuccessfulRequest(final @Nonnull TransactionRequest<?> req) {
417         successfulRequests.add(Verify.verifyNotNull(req));
418     }
419
420     final void recordFinishedRequest(final Response<?, ?> response) {
421         final Object last = successfulRequests.peekLast();
422         if (last instanceof IncrementSequence) {
423             ((IncrementSequence) last).incrementDelta();
424         } else {
425             successfulRequests.addLast(new IncrementSequence(response.getSequence()));
426         }
427     }
428
429     /**
430      * Abort this transaction. This is invoked only for read-only transactions and will result in an explicit message
431      * being sent to the backend.
432      */
433     final void abort() {
434         checkNotSealed();
435         parent.abortTransaction(this);
436
437         sendRequest(abortRequest(), resp -> {
438             LOG.debug("Transaction {} abort completed with {}", getIdentifier(), resp);
439             enqueuePurge();
440         });
441     }
442
443     final void abort(final VotingFuture<Void> ret) {
444         checkSealed();
445
446         sendDoAbort(t -> {
447             if (t instanceof TransactionAbortSuccess) {
448                 ret.voteYes();
449             } else if (t instanceof RequestFailure) {
450                 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
451             } else {
452                 ret.voteNo(new IllegalStateException("Unhandled response " + t.getClass()));
453             }
454
455             // This is a terminal request, hence we do not need to record it
456             LOG.debug("Transaction {} abort completed", this);
457             enqueuePurge();
458         });
459     }
460
461     final void enqueueAbort(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
462         checkNotSealed();
463         parent.abortTransaction(this);
464
465         enqueueRequest(abortRequest(), resp -> {
466             LOG.debug("Transaction {} abort completed with {}", getIdentifier(), resp);
467             // Purge will be sent by the predecessor's callback
468             if (callback != null) {
469                 callback.accept(resp);
470             }
471         }, enqueuedTicks);
472     }
473
474     final void enqueueDoAbort(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
475         enqueueRequest(new TransactionAbortRequest(getIdentifier(), nextSequence(), localActor()), callback,
476             enqueuedTicks);
477     }
478
479     final void sendDoAbort(final Consumer<Response<?, ?>> callback) {
480         sendRequest(new TransactionAbortRequest(getIdentifier(), nextSequence(), localActor()), callback);
481     }
482
483     /**
484      * Commit this transaction, possibly in a coordinated fashion.
485      *
486      * @param coordinated True if this transaction should be coordinated across multiple participants.
487      * @return Future completion
488      */
489     final ListenableFuture<Boolean> directCommit() {
490         checkReadWrite();
491         checkSealed();
492
493         // Precludes startReconnect() from interfering with the fast path
494         synchronized (this) {
495             if (STATE_UPDATER.compareAndSet(this, SEALED, FLUSHED)) {
496                 final SettableFuture<Boolean> ret = SettableFuture.create();
497                 sendRequest(Verify.verifyNotNull(commitRequest(false)), t -> {
498                     if (t instanceof TransactionCommitSuccess) {
499                         ret.set(Boolean.TRUE);
500                     } else if (t instanceof RequestFailure) {
501                         final Throwable cause = ((RequestFailure<?, ?>) t).getCause().unwrap();
502                         if (cause instanceof ClosedTransactionException) {
503                             // This is okay, as it indicates the transaction has been completed. It can happen
504                             // when we lose connectivity with the backend after it has received the request.
505                             ret.set(Boolean.TRUE);
506                         } else {
507                             ret.setException(cause);
508                         }
509                     } else {
510                         ret.setException(new IllegalStateException("Unhandled response " + t.getClass()));
511                     }
512
513                     // This is a terminal request, hence we do not need to record it
514                     LOG.debug("Transaction {} directCommit completed", this);
515                     enqueuePurge();
516                 });
517
518                 return ret;
519             }
520         }
521
522         // We have had some interference with successor injection, wait for it to complete and defer to the successor.
523         return awaitSuccessor().directCommit();
524     }
525
526     final void canCommit(final VotingFuture<?> ret) {
527         checkReadWrite();
528         checkSealed();
529
530         // Precludes startReconnect() from interfering with the fast path
531         synchronized (this) {
532             if (STATE_UPDATER.compareAndSet(this, SEALED, FLUSHED)) {
533                 final TransactionRequest<?> req = Verify.verifyNotNull(commitRequest(true));
534
535                 sendRequest(req, t -> {
536                     if (t instanceof TransactionCanCommitSuccess) {
537                         ret.voteYes();
538                     } else if (t instanceof RequestFailure) {
539                         ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
540                     } else {
541                         ret.voteNo(new IllegalStateException("Unhandled response " + t.getClass()));
542                     }
543
544                     recordSuccessfulRequest(req);
545                     LOG.debug("Transaction {} canCommit completed", this);
546                 });
547
548                 return;
549             }
550         }
551
552         // We have had some interference with successor injection, wait for it to complete and defer to the successor.
553         awaitSuccessor().canCommit(ret);
554     }
555
556     private AbstractProxyTransaction awaitSuccessor() {
557         return getSuccessorState().await();
558     }
559
560     final void preCommit(final VotingFuture<?> ret) {
561         checkReadWrite();
562         checkSealed();
563
564         final TransactionRequest<?> req = new TransactionPreCommitRequest(getIdentifier(), nextSequence(),
565             localActor());
566         sendRequest(req, t -> {
567             if (t instanceof TransactionPreCommitSuccess) {
568                 ret.voteYes();
569             } else if (t instanceof RequestFailure) {
570                 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
571             } else {
572                 ret.voteNo(new IllegalStateException("Unhandled response " + t.getClass()));
573             }
574
575             onPreCommitComplete(req);
576         });
577     }
578
579     private void onPreCommitComplete(final TransactionRequest<?> req) {
580         /*
581          * The backend has agreed that the transaction has entered PRE_COMMIT phase, meaning it will be committed
582          * to storage after the timeout completes.
583          *
584          * All state has been replicated to the backend, hence we do not need to keep it around. Retain only
585          * the precommit request, so we know which request to use for resync.
586          */
587         LOG.debug("Transaction {} preCommit completed, clearing successfulRequests", this);
588         successfulRequests.clear();
589
590         // TODO: this works, but can contain some useless state (like batched operations). Create an empty
591         //       equivalent of this request and store that.
592         recordSuccessfulRequest(req);
593     }
594
595     final void doCommit(final VotingFuture<?> ret) {
596         checkReadWrite();
597         checkSealed();
598
599         sendRequest(new TransactionDoCommitRequest(getIdentifier(), nextSequence(), localActor()), t -> {
600             if (t instanceof TransactionCommitSuccess) {
601                 ret.voteYes();
602             } else if (t instanceof RequestFailure) {
603                 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
604             } else {
605                 ret.voteNo(new IllegalStateException("Unhandled response " + t.getClass()));
606             }
607
608             LOG.debug("Transaction {} doCommit completed", this);
609
610             // Needed for ProxyHistory$Local data tree rebase points.
611             parent.completeTransaction(this);
612
613             enqueuePurge();
614         });
615     }
616
617     private void enqueuePurge() {
618         enqueuePurge(null);
619     }
620
621     final void enqueuePurge(final Consumer<Response<?, ?>> callback) {
622         // Purge request are dispatched internally, hence should not wait
623         enqueuePurge(callback, parent.currentTime());
624     }
625
626     final void enqueuePurge(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
627         LOG.debug("{}: initiating purge", this);
628
629         final State prev = state;
630         if (prev instanceof SuccessorState) {
631             ((SuccessorState) prev).setDone();
632         } else {
633             final boolean success = STATE_UPDATER.compareAndSet(this, prev, DONE);
634             if (!success) {
635                 LOG.warn("{}: moved from state {} while we were purging it", this, prev);
636             }
637         }
638
639         successfulRequests.clear();
640
641         enqueueRequest(new TransactionPurgeRequest(getIdentifier(), nextSequence(), localActor()), resp -> {
642             LOG.debug("{}: purge completed", this);
643             parent.purgeTransaction(this);
644
645             if (callback != null) {
646                 callback.accept(resp);
647             }
648         }, enqueuedTicks);
649     }
650
651     // Called with the connection unlocked
652     final synchronized void startReconnect() {
653         // At this point canCommit/directCommit are blocked, we assert a new successor state, retrieving the previous
654         // state. This method is called with the queue still unlocked.
655         final SuccessorState nextState = new SuccessorState();
656         final State prevState = STATE_UPDATER.getAndSet(this, nextState);
657
658         LOG.debug("Start reconnect of proxy {} previous state {}", this, prevState);
659         Verify.verify(!(prevState instanceof SuccessorState), "Proxy %s duplicate reconnect attempt after %s", this,
660             prevState);
661
662         // We have asserted a slow-path state, seal(), canCommit(), directCommit() are forced to slow paths, which will
663         // wait until we unblock nextState's latch before accessing state. Now we record prevState for later use and we
664         // are done.
665         nextState.setPrevState(prevState);
666     }
667
668     // Called with the connection locked
669     final void replayMessages(final ProxyHistory successorHistory, final Iterable<ConnectionEntry> enqueuedEntries) {
670         final SuccessorState local = getSuccessorState();
671         final State prevState = local.getPrevState();
672
673         final AbstractProxyTransaction successor = successorHistory.createTransactionProxy(getIdentifier(),
674             isSnapshotOnly(), local.isDone());
675         LOG.debug("{} created successor {}", this, successor);
676         local.setSuccessor(successor);
677
678         // Replay successful requests first
679         if (!successfulRequests.isEmpty()) {
680             // We need to find a good timestamp to use for successful requests, as we do not want to time them out
681             // nor create timing inconsistencies in the queue -- requests are expected to be ordered by their enqueue
682             // time. We will pick the time of the first entry available. If there is none, we will just use current
683             // time, as all other requests will get enqueued afterwards.
684             final ConnectionEntry firstInQueue = Iterables.getFirst(enqueuedEntries, null);
685             final long now = firstInQueue != null ? firstInQueue.getEnqueuedTicks() : parent.currentTime();
686
687             for (Object obj : successfulRequests) {
688                 if (obj instanceof TransactionRequest) {
689                     LOG.debug("Forwarding successful request {} to successor {}", obj, successor);
690                     successor.doReplayRequest((TransactionRequest<?>) obj, resp -> { }, now);
691                 } else {
692                     Verify.verify(obj instanceof IncrementSequence);
693                     final IncrementSequence increment = (IncrementSequence) obj;
694                     successor.doReplayRequest(new IncrementTransactionSequenceRequest(getIdentifier(),
695                         increment.getSequence(), localActor(), isSnapshotOnly(), increment.getDelta()), resp -> { },
696                         now);
697                     LOG.debug("Incrementing sequence {} to successor {}", obj, successor);
698                 }
699             }
700             LOG.debug("{} replayed {} successful requests", getIdentifier(), successfulRequests.size());
701             successfulRequests.clear();
702         }
703
704         // Now replay whatever is in the connection
705         final Iterator<ConnectionEntry> it = enqueuedEntries.iterator();
706         while (it.hasNext()) {
707             final ConnectionEntry e = it.next();
708             final Request<?, ?> req = e.getRequest();
709
710             if (getIdentifier().equals(req.getTarget())) {
711                 Verify.verify(req instanceof TransactionRequest, "Unhandled request %s", req);
712                 LOG.debug("Replaying queued request {} to successor {}", req, successor);
713                 successor.doReplayRequest((TransactionRequest<?>) req, e.getCallback(), e.getEnqueuedTicks());
714                 it.remove();
715             }
716         }
717
718         /*
719          * Check the state at which we have started the reconnect attempt. State transitions triggered while we were
720          * reconnecting have been forced to slow paths, which will be unlocked once we unblock the state latch
721          * at the end of this method.
722          */
723         if (SEALED.equals(prevState)) {
724             LOG.debug("Proxy {} reconnected while being sealed, propagating state to successor {}", this, successor);
725             final long enqueuedTicks = parent.currentTime();
726             final java.util.Optional<ModifyTransactionRequest> optState = flushState();
727             if (optState.isPresent()) {
728                 successor.handleReplayedRemoteRequest(optState.get(), null, enqueuedTicks);
729             }
730             if (successor.markSealed()) {
731                 successor.sealAndSend(Optional.of(enqueuedTicks));
732             }
733         }
734     }
735
736     /**
737      * Invoked from {@link #replayMessages(AbstractProxyTransaction, Iterable)} to have successor adopt an in-flight
738      * request.
739      *
740      * <p>
741      * Note: this method is invoked by the predecessor on the successor.
742      *
743      * @param request Request which needs to be forwarded
744      * @param callback Callback to be invoked once the request completes
745      * @param enqueuedTicks ticker-based time stamp when the request was enqueued
746      */
747     private void doReplayRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
748             final long enqueuedTicks) {
749         if (request instanceof AbstractLocalTransactionRequest) {
750             handleReplayedLocalRequest((AbstractLocalTransactionRequest<?>) request, callback, enqueuedTicks);
751         } else {
752             handleReplayedRemoteRequest(request, callback, enqueuedTicks);
753         }
754     }
755
756     // Called with the connection locked
757     final void finishReconnect() {
758         final SuccessorState local = getSuccessorState();
759         LOG.debug("Finishing reconnect of proxy {}", this);
760
761         // All done, release the latch, unblocking seal() and canCommit() slow paths
762         local.finish();
763     }
764
765     /**
766      * Invoked from a retired connection for requests which have been in-flight and need to be re-adjusted
767      * and forwarded to the successor connection.
768      *
769      * @param request Request to be forwarded
770      * @param callback Original callback
771      */
772     final void forwardRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
773         forwardToSuccessor(getSuccessorState().getSuccessor(), request, callback);
774     }
775
776     final void forwardToSuccessor(final AbstractProxyTransaction successor, final TransactionRequest<?> request,
777             final Consumer<Response<?, ?>> callback) {
778         if (successor instanceof LocalProxyTransaction) {
779             forwardToLocal((LocalProxyTransaction)successor, request, callback);
780         } else if (successor instanceof RemoteProxyTransaction) {
781             forwardToRemote((RemoteProxyTransaction)successor, request, callback);
782         } else {
783             throw new IllegalStateException("Unhandled successor " + successor);
784         }
785     }
786
787     final void replayRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
788             final long enqueuedTicks) {
789         getSuccessorState().getSuccessor().doReplayRequest(request, callback, enqueuedTicks);
790     }
791
792     abstract boolean isSnapshotOnly();
793
794     abstract void doDelete(YangInstanceIdentifier path);
795
796     abstract void doMerge(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
797
798     abstract void doWrite(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
799
800     abstract CheckedFuture<Boolean, ReadFailedException> doExists(YangInstanceIdentifier path);
801
802     abstract CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> doRead(YangInstanceIdentifier path);
803
804     @GuardedBy("this")
805     abstract java.util.Optional<ModifyTransactionRequest> flushState();
806
807     abstract TransactionRequest<?> abortRequest();
808
809     abstract TransactionRequest<?> commitRequest(boolean coordinated);
810
811     /**
812      * Replay a request originating in this proxy to a successor remote proxy.
813      */
814     abstract void forwardToRemote(RemoteProxyTransaction successor, TransactionRequest<?> request,
815             Consumer<Response<?, ?>> callback);
816
817     /**
818      * Replay a request originating in this proxy to a successor local proxy.
819      */
820     abstract void forwardToLocal(LocalProxyTransaction successor, TransactionRequest<?> request,
821             Consumer<Response<?, ?>> callback);
822
823     /**
824      * Invoked from {@link LocalProxyTransaction} when it replays its successful requests to its successor.
825      *
826      * <p>
827      * Note: this method is invoked by the predecessor on the successor.
828      *
829      * @param request Request which needs to be forwarded
830      * @param callback Callback to be invoked once the request completes
831      * @param enqueuedTicks Time stamp to use for enqueue time
832      */
833     abstract void handleReplayedLocalRequest(AbstractLocalTransactionRequest<?> request,
834             @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
835
836     /**
837      * Invoked from {@link RemoteProxyTransaction} when it replays its successful requests to its successor.
838      *
839      * <p>
840      * Note: this method is invoked by the predecessor on the successor.
841      *
842      * @param request Request which needs to be forwarded
843      * @param callback Callback to be invoked once the request completes
844      * @param enqueuedTicks Time stamp to use for enqueue time
845      */
846     abstract void handleReplayedRemoteRequest(TransactionRequest<?> request,
847             @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
848
849     @Override
850     public final String toString() {
851         return MoreObjects.toStringHelper(this).add("identifier", getIdentifier()).add("state", state).toString();
852     }
853 }