2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.databroker.actors.dds;
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;
15 import akka.actor.ActorRef;
16 import com.google.common.base.MoreObjects;
17 import com.google.common.collect.Iterables;
18 import com.google.common.util.concurrent.FluentFuture;
19 import com.google.common.util.concurrent.ListenableFuture;
20 import com.google.common.util.concurrent.SettableFuture;
21 import java.util.ArrayDeque;
22 import java.util.Deque;
23 import java.util.Iterator;
24 import java.util.Optional;
25 import java.util.OptionalLong;
26 import java.util.concurrent.CountDownLatch;
27 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
28 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
29 import java.util.function.Consumer;
30 import org.checkerframework.checker.lock.qual.GuardedBy;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.opendaylight.controller.cluster.access.client.ConnectionEntry;
34 import org.opendaylight.controller.cluster.access.commands.AbstractLocalTransactionRequest;
35 import org.opendaylight.controller.cluster.access.commands.ClosedTransactionException;
36 import org.opendaylight.controller.cluster.access.commands.IncrementTransactionSequenceRequest;
37 import org.opendaylight.controller.cluster.access.commands.ModifyTransactionRequest;
38 import org.opendaylight.controller.cluster.access.commands.TransactionAbortRequest;
39 import org.opendaylight.controller.cluster.access.commands.TransactionAbortSuccess;
40 import org.opendaylight.controller.cluster.access.commands.TransactionCanCommitSuccess;
41 import org.opendaylight.controller.cluster.access.commands.TransactionCommitSuccess;
42 import org.opendaylight.controller.cluster.access.commands.TransactionDoCommitRequest;
43 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitRequest;
44 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitSuccess;
45 import org.opendaylight.controller.cluster.access.commands.TransactionPurgeRequest;
46 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
47 import org.opendaylight.controller.cluster.access.concepts.Request;
48 import org.opendaylight.controller.cluster.access.concepts.RequestFailure;
49 import org.opendaylight.controller.cluster.access.concepts.Response;
50 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
51 import org.opendaylight.yangtools.concepts.Identifiable;
52 import org.opendaylight.yangtools.yang.common.Empty;
53 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
54 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * Class translating transaction operations towards a particular backend shard.
62 * This class is not safe to access from multiple application threads, as is usual for transactions. Internal state
63 * transitions coming from interactions with backend are expected to be thread-safe.
66 * This class interacts with the queueing mechanism in ClientActorBehavior, hence once we arrive at a decision
67 * to use either a local or remote implementation, we are stuck with it. We can re-evaluate on the next transaction.
69 * @author Robert Varga
71 // FIXME: sealed when we have JDK17+
72 abstract class AbstractProxyTransaction implements Identifiable<TransactionIdentifier> {
74 * Marker object used instead of read-type of requests, which are satisfied only once. This has a lower footprint
75 * and allows compressing multiple requests into a single entry. This class is not thread-safe.
77 private static final class IncrementSequence {
78 private final long sequence;
79 private long delta = 0;
81 IncrementSequence(final long sequence) {
82 this.sequence = sequence;
93 void incrementDelta() {
99 * Base class for representing logical state of this proxy. See individual instantiations and {@link SuccessorState}
102 private static class State {
103 private final String string;
105 State(final String string) {
106 this.string = requireNonNull(string);
110 public final String toString() {
116 * State class used when a successor has interfered. Contains coordinator latch, the successor and previous state.
117 * This is a temporary state introduced during reconnection process and is necessary for correct state hand-off
118 * between the old connection (potentially being accessed by the user) and the new connection (being cleaned up
122 * When a user operation encounters this state, it synchronizes on the it and wait until reconnection completes,
123 * at which point the request is routed to the successor transaction. This is a relatively heavy-weight solution
124 * to the problem of state transfer, but the user will observe it only if the race condition is hit.
126 private static class SuccessorState extends State {
127 private final CountDownLatch latch = new CountDownLatch(1);
128 private AbstractProxyTransaction successor;
129 private State prevState;
132 private boolean done;
138 // Synchronize with succession process and return the successor
139 AbstractProxyTransaction await() {
142 } catch (InterruptedException e) {
143 LOG.warn("Interrupted while waiting for latch of {}", successor);
144 throw new IllegalStateException(e);
153 State getPrevState() {
154 return verifyNotNull(prevState, "Attempted to access previous state, which was not set");
157 void setPrevState(final State prevState) {
158 verify(this.prevState == null, "Attempted to set previous state to %s when we already have %s", prevState,
160 this.prevState = requireNonNull(prevState);
161 // We cannot have duplicate successor states, so this check is sufficient
162 done = DONE.equals(prevState);
165 // To be called from safe contexts, where successor is known to be completed
166 AbstractProxyTransaction getSuccessor() {
167 return verifyNotNull(successor);
170 void setSuccessor(final AbstractProxyTransaction successor) {
171 verify(this.successor == null, "Attempted to set successor to %s when we already have %s", successor,
173 this.successor = requireNonNull(successor);
185 private static final Logger LOG = LoggerFactory.getLogger(AbstractProxyTransaction.class);
186 private static final AtomicIntegerFieldUpdater<AbstractProxyTransaction> SEALED_UPDATER =
187 AtomicIntegerFieldUpdater.newUpdater(AbstractProxyTransaction.class, "sealed");
188 private static final AtomicReferenceFieldUpdater<AbstractProxyTransaction, State> STATE_UPDATER =
189 AtomicReferenceFieldUpdater.newUpdater(AbstractProxyTransaction.class, State.class, "state");
192 * Transaction has been open and is being actively worked on.
194 private static final State OPEN = new State("OPEN");
197 * Transaction has been sealed by the user, but it has not completed flushing to the backed, yet. This is
198 * a transition state, as we are waiting for the user to initiate commit procedures.
201 * Since the reconnect mechanics relies on state replay for transactions, this state needs to be flushed into the
202 * queue to re-create state in successor transaction (which may be based on different messages as locality may have
203 * changed). Hence the transition to {@link #FLUSHED} state needs to be handled in a thread-safe manner.
205 private static final State SEALED = new State("SEALED");
208 * Transaction state has been flushed into the queue, i.e. it is visible by the successor and potentially
209 * the backend. At this point the transaction does not hold any state besides successful requests, all other state
210 * is held either in the connection's queue or the successor object.
213 * Transition to this state indicates we have all input from the user we need to initiate the correct commit
216 private static final State FLUSHED = new State("FLUSHED");
219 * Transaction state has been completely resolved, we have received confirmation of the transaction fate from
220 * the backend. The only remaining task left to do is finishing up the state cleanup, which is done via purge
221 * request. We need to hang on to the transaction until that is done, as we have to make sure backend completes
222 * purging its state -- otherwise we could have a leak on the backend.
224 private static final State DONE = new State("DONE");
226 // Touched from client actor thread only
227 private final Deque<Object> successfulRequests = new ArrayDeque<>();
228 private final ProxyHistory parent;
230 // Accessed from user thread only, which may not access this object concurrently
231 private long sequence;
234 * Atomic state-keeping is required to synchronize the process of propagating completed transaction state towards
235 * the backend -- which may include a successor.
237 * Successor, unlike {@link AbstractProxyTransaction#seal()} is triggered from the client actor thread, which means
238 * the successor placement needs to be atomic with regard to the application thread.
240 * In the common case, the application thread performs performs the seal operations and then "immediately" sends
241 * the corresponding message. The uncommon case is when the seal and send operations race with a connect completion
242 * or timeout, when a successor is injected.
244 * This leaves the problem of needing to completely transferring state just after all queued messages are replayed
245 * after a successor was injected, so that it can be properly sealed if we are racing. Further complication comes
246 * from lock ordering, where the successor injection works with a locked queue and locks proxy objects -- leading
247 * to a potential AB-BA deadlock in case of a naive implementation.
249 * For tracking user-visible state we use a single volatile int, which is flipped atomically from 0 to 1 exactly
250 * once in {@link AbstractProxyTransaction#seal()}. That keeps common operations fast, as they need to perform
251 * only a single volatile read to assert state correctness.
253 * For synchronizing client actor (successor-injecting) and user (commit-driving) thread, we keep a separate state
254 * variable. It uses pre-allocated objects for fast paths (i.e. no successor present) and a per-transition object
255 * for slow paths (when successor is injected/present).
257 private volatile int sealed;
258 private volatile State state;
260 AbstractProxyTransaction(final ProxyHistory parent, final boolean isDone) {
261 this.parent = requireNonNull(parent);
264 // DONE implies previous seal operation completed
271 final void executeInActor(final Runnable command) {
272 parent.context().executeInActor(behavior -> {
278 final ActorRef localActor() {
279 return parent.localActor();
282 final void incrementSequence(final long delta) {
284 LOG.debug("Transaction {} incremented sequence to {}", this, sequence);
287 final long nextSequence() {
288 final long ret = sequence++;
289 LOG.debug("Transaction {} allocated sequence {}", this, ret);
293 final void delete(final YangInstanceIdentifier path) {
299 final void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
305 final void write(final YangInstanceIdentifier path, final NormalizedNode data) {
311 final FluentFuture<Boolean> exists(final YangInstanceIdentifier path) {
313 return doExists(path);
316 final FluentFuture<Optional<NormalizedNode>> read(final YangInstanceIdentifier path) {
321 final void enqueueRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
322 final long enqueuedTicks) {
323 LOG.debug("Transaction proxy {} enqueing request {} callback {}", this, request, callback);
324 parent.enqueueRequest(request, callback, enqueuedTicks);
327 final void sendRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
328 LOG.debug("Transaction proxy {} sending request {} callback {}", this, request, callback);
329 parent.sendRequest(request, callback);
333 * Seal this transaction before it is either committed or aborted. This method should only be invoked from
334 * application thread.
337 // Transition user-visible state first
338 final boolean success = markSealed();
339 checkState(success, "Proxy %s was already sealed", getIdentifier());
341 if (!sealAndSend(OptionalLong.empty())) {
347 * Internal seal propagation method, invoked when we have raced with reconnection thread. Note that there may have
348 * been multiple reconnects, so we have to make sure the action is propagate through all intermediate instances.
350 private void sealSuccessor() {
351 // Slow path: wait for the successor to complete
352 final AbstractProxyTransaction successor = awaitSuccessor();
354 // At this point the successor has completed transition and is possibly visible by the user thread, which is
355 // still stuck here. The successor has not seen final part of our state, nor the fact it is sealed.
356 // Propagate state and seal the successor.
357 final Optional<ModifyTransactionRequest> optState = flushState();
358 if (optState.isPresent()) {
359 forwardToSuccessor(successor, optState.get(), null);
361 successor.predecessorSealed();
364 private void predecessorSealed() {
365 if (markSealed() && !sealAndSend(OptionalLong.empty())) {
371 * Seal this transaction. If this method reports false, the caller needs to deal with propagating the seal operation
372 * towards the successor.
374 * @return True if seal operation was successful, false if this proxy has a successor.
381 * Seal this transaction and potentially send it out towards the backend. If this method reports false, the caller
382 * needs to deal with propagating the seal operation towards the successor.
384 * @param enqueuedTicks Enqueue ticks when this is invoked from replay path.
385 * @return True if seal operation was successful, false if this proxy has a successor.
387 boolean sealAndSend(final OptionalLong enqueuedTicks) {
391 private boolean sealState() {
392 parent.onTransactionSealed(this);
393 // Transition internal state to sealed and detect presence of a successor
394 return STATE_UPDATER.compareAndSet(this, OPEN, SEALED);
398 * Mark this proxy as having been sealed.
400 * @return True if this call has transitioned to sealed state.
402 final boolean markSealed() {
403 return SEALED_UPDATER.compareAndSet(this, 0, 1);
406 private void checkNotSealed() {
407 checkState(sealed == 0, "Transaction %s has already been sealed", getIdentifier());
410 private void checkSealed() {
411 checkState(sealed != 0, "Transaction %s has not been sealed yet", getIdentifier());
414 private SuccessorState getSuccessorState() {
415 final State local = state;
416 verify(local instanceof SuccessorState, "State %s has unexpected class", local);
417 return (SuccessorState) local;
420 private void checkReadWrite() {
421 if (isSnapshotOnly()) {
422 throw new UnsupportedOperationException("Transaction " + getIdentifier() + " is a read-only snapshot");
426 final void recordSuccessfulRequest(final @NonNull TransactionRequest<?> req) {
427 successfulRequests.add(verifyNotNull(req));
430 final void recordFinishedRequest(final Response<?, ?> response) {
431 final Object last = successfulRequests.peekLast();
432 if (last instanceof IncrementSequence) {
433 ((IncrementSequence) last).incrementDelta();
435 successfulRequests.addLast(new IncrementSequence(response.getSequence()));
440 * Abort this transaction. This is invoked only for read-only transactions and will result in an explicit message
441 * being sent to the backend.
445 parent.abortTransaction(this);
447 sendRequest(abortRequest(), resp -> {
448 LOG.debug("Transaction {} abort completed with {}", getIdentifier(), resp);
453 final void abort(final VotingFuture<Empty> ret) {
457 if (t instanceof TransactionAbortSuccess) {
459 } else if (t instanceof RequestFailure) {
460 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
462 ret.voteNo(unhandledResponseException(t));
465 // This is a terminal request, hence we do not need to record it
466 LOG.debug("Transaction {} abort completed", this);
471 final void enqueueAbort(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
473 parent.abortTransaction(this);
475 enqueueRequest(abortRequest(), resp -> {
476 LOG.debug("Transaction {} abort completed with {}", getIdentifier(), resp);
477 // Purge will be sent by the predecessor's callback
478 if (callback != null) {
479 callback.accept(resp);
484 final void enqueueDoAbort(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
485 enqueueRequest(new TransactionAbortRequest(getIdentifier(), nextSequence(), localActor()), callback,
489 final void sendDoAbort(final Consumer<Response<?, ?>> callback) {
490 sendRequest(new TransactionAbortRequest(getIdentifier(), nextSequence(), localActor()), callback);
494 * Commit this transaction, possibly in a coordinated fashion.
496 * @param coordinated True if this transaction should be coordinated across multiple participants.
497 * @return Future completion
499 final ListenableFuture<Boolean> directCommit() {
503 // Precludes startReconnect() from interfering with the fast path
504 synchronized (this) {
505 if (STATE_UPDATER.compareAndSet(this, SEALED, FLUSHED)) {
506 final SettableFuture<Boolean> ret = SettableFuture.create();
507 sendRequest(verifyNotNull(commitRequest(false)), t -> {
508 if (t instanceof TransactionCommitSuccess) {
509 ret.set(Boolean.TRUE);
510 } else if (t instanceof RequestFailure) {
511 final Throwable cause = ((RequestFailure<?, ?>) t).getCause().unwrap();
512 if (cause instanceof ClosedTransactionException) {
513 // This is okay, as it indicates the transaction has been completed. It can happen
514 // when we lose connectivity with the backend after it has received the request.
515 ret.set(Boolean.TRUE);
517 ret.setException(cause);
520 ret.setException(unhandledResponseException(t));
523 // This is a terminal request, hence we do not need to record it
524 LOG.debug("Transaction {} directCommit completed", this);
532 // We have had some interference with successor injection, wait for it to complete and defer to the successor.
533 return awaitSuccessor().directCommit();
536 final void canCommit(final VotingFuture<?> ret) {
540 // Precludes startReconnect() from interfering with the fast path
541 synchronized (this) {
542 if (STATE_UPDATER.compareAndSet(this, SEALED, FLUSHED)) {
543 final TransactionRequest<?> req = verifyNotNull(commitRequest(true));
545 sendRequest(req, t -> {
546 if (t instanceof TransactionCanCommitSuccess) {
548 } else if (t instanceof RequestFailure) {
549 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
551 ret.voteNo(unhandledResponseException(t));
554 recordSuccessfulRequest(req);
555 LOG.debug("Transaction {} canCommit completed", this);
562 // We have had some interference with successor injection, wait for it to complete and defer to the successor.
563 awaitSuccessor().canCommit(ret);
566 private AbstractProxyTransaction awaitSuccessor() {
567 return getSuccessorState().await();
570 final void preCommit(final VotingFuture<?> ret) {
574 final TransactionRequest<?> req = new TransactionPreCommitRequest(getIdentifier(), nextSequence(),
576 sendRequest(req, t -> {
577 if (t instanceof TransactionPreCommitSuccess) {
579 } else if (t instanceof RequestFailure) {
580 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
582 ret.voteNo(unhandledResponseException(t));
585 onPreCommitComplete(req);
589 private void onPreCommitComplete(final TransactionRequest<?> req) {
591 * The backend has agreed that the transaction has entered PRE_COMMIT phase, meaning it will be committed
592 * to storage after the timeout completes.
594 * All state has been replicated to the backend, hence we do not need to keep it around. Retain only
595 * the precommit request, so we know which request to use for resync.
597 LOG.debug("Transaction {} preCommit completed, clearing successfulRequests", this);
598 successfulRequests.clear();
600 // TODO: this works, but can contain some useless state (like batched operations). Create an empty
601 // equivalent of this request and store that.
602 recordSuccessfulRequest(req);
605 final void doCommit(final VotingFuture<?> ret) {
609 sendRequest(new TransactionDoCommitRequest(getIdentifier(), nextSequence(), localActor()), t -> {
610 if (t instanceof TransactionCommitSuccess) {
612 } else if (t instanceof RequestFailure) {
613 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
615 ret.voteNo(unhandledResponseException(t));
618 LOG.debug("Transaction {} doCommit completed", this);
620 // Needed for ProxyHistory$Local data tree rebase points.
621 parent.completeTransaction(this);
627 private void enqueuePurge() {
631 final void enqueuePurge(final Consumer<Response<?, ?>> callback) {
632 // Purge request are dispatched internally, hence should not wait
633 enqueuePurge(callback, parent.currentTime());
636 final void enqueuePurge(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
637 LOG.debug("{}: initiating purge", this);
639 final State prev = state;
640 if (prev instanceof SuccessorState) {
641 ((SuccessorState) prev).setDone();
643 final boolean success = STATE_UPDATER.compareAndSet(this, prev, DONE);
645 LOG.warn("{}: moved from state {} while we were purging it", this, prev);
649 successfulRequests.clear();
651 enqueueRequest(new TransactionPurgeRequest(getIdentifier(), nextSequence(), localActor()), resp -> {
652 LOG.debug("{}: purge completed", this);
653 parent.purgeTransaction(this);
655 if (callback != null) {
656 callback.accept(resp);
661 // Called with the connection unlocked
662 final synchronized void startReconnect() {
663 // At this point canCommit/directCommit are blocked, we assert a new successor state, retrieving the previous
664 // state. This method is called with the queue still unlocked.
665 final SuccessorState nextState = new SuccessorState();
666 final State prevState = STATE_UPDATER.getAndSet(this, nextState);
668 LOG.debug("Start reconnect of proxy {} previous state {}", this, prevState);
669 verify(!(prevState instanceof SuccessorState), "Proxy %s duplicate reconnect attempt after %s", this,
672 // We have asserted a slow-path state, seal(), canCommit(), directCommit() are forced to slow paths, which will
673 // wait until we unblock nextState's latch before accessing state. Now we record prevState for later use and we
675 nextState.setPrevState(prevState);
678 // Called with the connection locked
679 final void replayMessages(final ProxyHistory successorHistory, final Iterable<ConnectionEntry> enqueuedEntries) {
680 final SuccessorState local = getSuccessorState();
681 final State prevState = local.getPrevState();
683 final AbstractProxyTransaction successor = successorHistory.createTransactionProxy(getIdentifier(),
684 isSnapshotOnly(), local.isDone());
685 LOG.debug("{} created successor {}", this, successor);
686 local.setSuccessor(successor);
688 // Replay successful requests first
689 if (!successfulRequests.isEmpty()) {
690 // We need to find a good timestamp to use for successful requests, as we do not want to time them out
691 // nor create timing inconsistencies in the queue -- requests are expected to be ordered by their enqueue
692 // time. We will pick the time of the first entry available. If there is none, we will just use current
693 // time, as all other requests will get enqueued afterwards.
694 final ConnectionEntry firstInQueue = Iterables.getFirst(enqueuedEntries, null);
695 final long now = firstInQueue != null ? firstInQueue.getEnqueuedTicks() : parent.currentTime();
697 for (Object obj : successfulRequests) {
698 if (obj instanceof TransactionRequest) {
699 LOG.debug("Forwarding successful request {} to successor {}", obj, successor);
700 successor.doReplayRequest((TransactionRequest<?>) obj, resp -> { /*NOOP*/ }, now);
702 verify(obj instanceof IncrementSequence);
703 final IncrementSequence increment = (IncrementSequence) obj;
704 successor.doReplayRequest(new IncrementTransactionSequenceRequest(getIdentifier(),
705 increment.getSequence(), localActor(), isSnapshotOnly(),
706 increment.getDelta()), resp -> { /*NOOP*/ }, now);
707 LOG.debug("Incrementing sequence {} to successor {}", obj, successor);
710 LOG.debug("{} replayed {} successful requests", getIdentifier(), successfulRequests.size());
711 successfulRequests.clear();
714 // Now replay whatever is in the connection
715 final Iterator<ConnectionEntry> it = enqueuedEntries.iterator();
716 while (it.hasNext()) {
717 final ConnectionEntry e = it.next();
718 final Request<?, ?> req = e.getRequest();
720 if (getIdentifier().equals(req.getTarget())) {
721 verify(req instanceof TransactionRequest, "Unhandled request %s", req);
722 LOG.debug("Replaying queued request {} to successor {}", req, successor);
723 successor.doReplayRequest((TransactionRequest<?>) req, e.getCallback(), e.getEnqueuedTicks());
729 * Check the state at which we have started the reconnect attempt. State transitions triggered while we were
730 * reconnecting have been forced to slow paths, which will be unlocked once we unblock the state latch
731 * at the end of this method.
733 if (SEALED.equals(prevState)) {
734 LOG.debug("Proxy {} reconnected while being sealed, propagating state to successor {}", this, successor);
735 final long enqueuedTicks = parent.currentTime();
736 final Optional<ModifyTransactionRequest> optState = flushState();
737 if (optState.isPresent()) {
738 successor.handleReplayedRemoteRequest(optState.get(), null, enqueuedTicks);
740 if (successor.markSealed()) {
741 successor.sealAndSend(OptionalLong.of(enqueuedTicks));
747 * Invoked from {@link #replayMessages(AbstractProxyTransaction, Iterable)} to have successor adopt an in-flight
751 * Note: this method is invoked by the predecessor on the successor.
753 * @param request Request which needs to be forwarded
754 * @param callback Callback to be invoked once the request completes
755 * @param enqueuedTicks ticker-based time stamp when the request was enqueued
757 private void doReplayRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
758 final long enqueuedTicks) {
759 if (request instanceof AbstractLocalTransactionRequest) {
760 handleReplayedLocalRequest((AbstractLocalTransactionRequest<?>) request, callback, enqueuedTicks);
762 handleReplayedRemoteRequest(request, callback, enqueuedTicks);
766 // Called with the connection locked
767 final void finishReconnect() {
768 final SuccessorState local = getSuccessorState();
769 LOG.debug("Finishing reconnect of proxy {}", this);
771 // All done, release the latch, unblocking seal() and canCommit() slow paths
776 * Invoked from a retired connection for requests which have been in-flight and need to be re-adjusted
777 * and forwarded to the successor connection.
779 * @param request Request to be forwarded
780 * @param callback Original callback
782 final void forwardRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
783 forwardToSuccessor(getSuccessorState().getSuccessor(), request, callback);
786 final void forwardToSuccessor(final AbstractProxyTransaction successor, final TransactionRequest<?> request,
787 final Consumer<Response<?, ?>> callback) {
788 if (successor instanceof LocalProxyTransaction) {
789 forwardToLocal((LocalProxyTransaction)successor, request, callback);
790 } else if (successor instanceof RemoteProxyTransaction) {
791 forwardToRemote((RemoteProxyTransaction)successor, request, callback);
793 throw new IllegalStateException("Unhandled successor " + successor);
797 final void replayRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
798 final long enqueuedTicks) {
799 getSuccessorState().getSuccessor().doReplayRequest(request, callback, enqueuedTicks);
802 abstract boolean isSnapshotOnly();
804 abstract void doDelete(YangInstanceIdentifier path);
806 abstract void doMerge(YangInstanceIdentifier path, NormalizedNode data);
808 abstract void doWrite(YangInstanceIdentifier path, NormalizedNode data);
810 abstract FluentFuture<Boolean> doExists(YangInstanceIdentifier path);
812 abstract FluentFuture<Optional<NormalizedNode>> doRead(YangInstanceIdentifier path);
815 abstract Optional<ModifyTransactionRequest> flushState();
817 abstract TransactionRequest<?> abortRequest();
819 abstract TransactionRequest<?> commitRequest(boolean coordinated);
822 * Replay a request originating in this proxy to a successor remote proxy.
824 abstract void forwardToRemote(RemoteProxyTransaction successor, TransactionRequest<?> request,
825 Consumer<Response<?, ?>> callback);
828 * Replay a request originating in this proxy to a successor local proxy.
830 abstract void forwardToLocal(LocalProxyTransaction successor, TransactionRequest<?> request,
831 Consumer<Response<?, ?>> callback);
834 * Invoked from {@link LocalProxyTransaction} when it replays its successful requests to its successor.
837 * Note: this method is invoked by the predecessor on the successor.
839 * @param request Request which needs to be forwarded
840 * @param callback Callback to be invoked once the request completes
841 * @param enqueuedTicks Time stamp to use for enqueue time
843 abstract void handleReplayedLocalRequest(AbstractLocalTransactionRequest<?> request,
844 @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
847 * Invoked from {@link RemoteProxyTransaction} when it replays its successful requests to its successor.
850 * Note: this method is invoked by the predecessor on the successor.
852 * @param request Request which needs to be forwarded
853 * @param callback Callback to be invoked once the request completes
854 * @param enqueuedTicks Time stamp to use for enqueue time
856 abstract void handleReplayedRemoteRequest(TransactionRequest<?> request,
857 @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
859 static final @NonNull IllegalArgumentException unhandledRequest(final TransactionRequest<?> request) {
860 return new IllegalArgumentException("Unhandled request " + request);
863 private static @NonNull IllegalStateException unhandledResponseException(final Response<?, ?> resp) {
864 return new IllegalStateException("Unhandled response " + resp.getClass());
868 public final String toString() {
869 return MoreObjects.toStringHelper(this).add("identifier", getIdentifier()).add("state", state).toString();