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 abstract class AbstractProxyTransaction implements Identifiable<TransactionIdentifier> {
73 * Marker object used instead of read-type of requests, which are satisfied only once. This has a lower footprint
74 * and allows compressing multiple requests into a single entry. This class is not thread-safe.
76 private static final class IncrementSequence {
77 private final long sequence;
78 private long delta = 0;
80 IncrementSequence(final long sequence) {
81 this.sequence = sequence;
92 void incrementDelta() {
98 * Base class for representing logical state of this proxy. See individual instantiations and {@link SuccessorState}
101 private static class State {
102 private final String string;
104 State(final String string) {
105 this.string = requireNonNull(string);
109 public final String toString() {
115 * State class used when a successor has interfered. Contains coordinator latch, the successor and previous state.
116 * This is a temporary state introduced during reconnection process and is necessary for correct state hand-off
117 * between the old connection (potentially being accessed by the user) and the new connection (being cleaned up
121 * When a user operation encounters this state, it synchronizes on the it and wait until reconnection completes,
122 * at which point the request is routed to the successor transaction. This is a relatively heavy-weight solution
123 * to the problem of state transfer, but the user will observe it only if the race condition is hit.
125 private static class SuccessorState extends State {
126 private final CountDownLatch latch = new CountDownLatch(1);
127 private AbstractProxyTransaction successor;
128 private State prevState;
131 private boolean done;
137 // Synchronize with succession process and return the successor
138 AbstractProxyTransaction await() {
141 } catch (InterruptedException e) {
142 LOG.warn("Interrupted while waiting for latch of {}", successor);
143 throw new RuntimeException(e);
152 State getPrevState() {
153 return verifyNotNull(prevState, "Attempted to access previous state, which was not set");
156 void setPrevState(final State prevState) {
157 verify(this.prevState == null, "Attempted to set previous state to %s when we already have %s", prevState,
159 this.prevState = requireNonNull(prevState);
160 // We cannot have duplicate successor states, so this check is sufficient
161 done = DONE.equals(prevState);
164 // To be called from safe contexts, where successor is known to be completed
165 AbstractProxyTransaction getSuccessor() {
166 return verifyNotNull(successor);
169 void setSuccessor(final AbstractProxyTransaction successor) {
170 verify(this.successor == null, "Attempted to set successor to %s when we already have %s", successor,
172 this.successor = requireNonNull(successor);
184 private static final Logger LOG = LoggerFactory.getLogger(AbstractProxyTransaction.class);
185 private static final AtomicIntegerFieldUpdater<AbstractProxyTransaction> SEALED_UPDATER =
186 AtomicIntegerFieldUpdater.newUpdater(AbstractProxyTransaction.class, "sealed");
187 private static final AtomicReferenceFieldUpdater<AbstractProxyTransaction, State> STATE_UPDATER =
188 AtomicReferenceFieldUpdater.newUpdater(AbstractProxyTransaction.class, State.class, "state");
191 * Transaction has been open and is being actively worked on.
193 private static final State OPEN = new State("OPEN");
196 * Transaction has been sealed by the user, but it has not completed flushing to the backed, yet. This is
197 * a transition state, as we are waiting for the user to initiate commit procedures.
200 * Since the reconnect mechanics relies on state replay for transactions, this state needs to be flushed into the
201 * queue to re-create state in successor transaction (which may be based on different messages as locality may have
202 * changed). Hence the transition to {@link #FLUSHED} state needs to be handled in a thread-safe manner.
204 private static final State SEALED = new State("SEALED");
207 * Transaction state has been flushed into the queue, i.e. it is visible by the successor and potentially
208 * the backend. At this point the transaction does not hold any state besides successful requests, all other state
209 * is held either in the connection's queue or the successor object.
212 * Transition to this state indicates we have all input from the user we need to initiate the correct commit
215 private static final State FLUSHED = new State("FLUSHED");
218 * Transaction state has been completely resolved, we have received confirmation of the transaction fate from
219 * the backend. The only remaining task left to do is finishing up the state cleanup, which is done via purge
220 * request. We need to hang on to the transaction until that is done, as we have to make sure backend completes
221 * purging its state -- otherwise we could have a leak on the backend.
223 private static final State DONE = new State("DONE");
225 // Touched from client actor thread only
226 private final Deque<Object> successfulRequests = new ArrayDeque<>();
227 private final ProxyHistory parent;
229 // Accessed from user thread only, which may not access this object concurrently
230 private long sequence;
233 * Atomic state-keeping is required to synchronize the process of propagating completed transaction state towards
234 * the backend -- which may include a successor.
236 * Successor, unlike {@link AbstractProxyTransaction#seal()} is triggered from the client actor thread, which means
237 * the successor placement needs to be atomic with regard to the application thread.
239 * In the common case, the application thread performs performs the seal operations and then "immediately" sends
240 * the corresponding message. The uncommon case is when the seal and send operations race with a connect completion
241 * or timeout, when a successor is injected.
243 * This leaves the problem of needing to completely transferring state just after all queued messages are replayed
244 * after a successor was injected, so that it can be properly sealed if we are racing. Further complication comes
245 * from lock ordering, where the successor injection works with a locked queue and locks proxy objects -- leading
246 * to a potential AB-BA deadlock in case of a naive implementation.
248 * For tracking user-visible state we use a single volatile int, which is flipped atomically from 0 to 1 exactly
249 * once in {@link AbstractProxyTransaction#seal()}. That keeps common operations fast, as they need to perform
250 * only a single volatile read to assert state correctness.
252 * For synchronizing client actor (successor-injecting) and user (commit-driving) thread, we keep a separate state
253 * variable. It uses pre-allocated objects for fast paths (i.e. no successor present) and a per-transition object
254 * for slow paths (when successor is injected/present).
256 private volatile int sealed;
257 private volatile State state;
259 AbstractProxyTransaction(final ProxyHistory parent, final boolean isDone) {
260 this.parent = requireNonNull(parent);
263 // DONE implies previous seal operation completed
270 final void executeInActor(final Runnable command) {
271 parent.context().executeInActor(behavior -> {
277 final ActorRef localActor() {
278 return parent.localActor();
281 final void incrementSequence(final long delta) {
283 LOG.debug("Transaction {} incremented sequence to {}", this, sequence);
286 final long nextSequence() {
287 final long ret = sequence++;
288 LOG.debug("Transaction {} allocated sequence {}", this, ret);
292 final void delete(final YangInstanceIdentifier path) {
298 final void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
304 final void write(final YangInstanceIdentifier path, final NormalizedNode data) {
310 final FluentFuture<Boolean> exists(final YangInstanceIdentifier path) {
312 return doExists(path);
315 final FluentFuture<Optional<NormalizedNode>> read(final YangInstanceIdentifier path) {
320 final void enqueueRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
321 final long enqueuedTicks) {
322 LOG.debug("Transaction proxy {} enqueing request {} callback {}", this, request, callback);
323 parent.enqueueRequest(request, callback, enqueuedTicks);
326 final void sendRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
327 LOG.debug("Transaction proxy {} sending request {} callback {}", this, request, callback);
328 parent.sendRequest(request, callback);
332 * Seal this transaction before it is either committed or aborted. This method should only be invoked from
333 * application thread.
336 // Transition user-visible state first
337 final boolean success = markSealed();
338 checkState(success, "Proxy %s was already sealed", getIdentifier());
340 if (!sealAndSend(OptionalLong.empty())) {
346 * Internal seal propagation method, invoked when we have raced with reconnection thread. Note that there may have
347 * been multiple reconnects, so we have to make sure the action is propagate through all intermediate instances.
349 private void sealSuccessor() {
350 // Slow path: wait for the successor to complete
351 final AbstractProxyTransaction successor = awaitSuccessor();
353 // At this point the successor has completed transition and is possibly visible by the user thread, which is
354 // still stuck here. The successor has not seen final part of our state, nor the fact it is sealed.
355 // Propagate state and seal the successor.
356 final Optional<ModifyTransactionRequest> optState = flushState();
357 if (optState.isPresent()) {
358 forwardToSuccessor(successor, optState.get(), null);
360 successor.predecessorSealed();
363 private void predecessorSealed() {
364 if (markSealed() && !sealAndSend(OptionalLong.empty())) {
370 * Seal this transaction. If this method reports false, the caller needs to deal with propagating the seal operation
371 * towards the successor.
373 * @return True if seal operation was successful, false if this proxy has a successor.
380 * Seal this transaction and potentially send it out towards the backend. If this method reports false, the caller
381 * needs to deal with propagating the seal operation towards the successor.
383 * @param enqueuedTicks Enqueue ticks when this is invoked from replay path.
384 * @return True if seal operation was successful, false if this proxy has a successor.
386 boolean sealAndSend(final OptionalLong enqueuedTicks) {
390 private boolean sealState() {
391 parent.onTransactionSealed(this);
392 // Transition internal state to sealed and detect presence of a successor
393 return STATE_UPDATER.compareAndSet(this, OPEN, SEALED);
397 * Mark this proxy as having been sealed.
399 * @return True if this call has transitioned to sealed state.
401 final boolean markSealed() {
402 return SEALED_UPDATER.compareAndSet(this, 0, 1);
405 private void checkNotSealed() {
406 checkState(sealed == 0, "Transaction %s has already been sealed", getIdentifier());
409 private void checkSealed() {
410 checkState(sealed != 0, "Transaction %s has not been sealed yet", getIdentifier());
413 private SuccessorState getSuccessorState() {
414 final State local = state;
415 verify(local instanceof SuccessorState, "State %s has unexpected class", local);
416 return (SuccessorState) local;
419 private void checkReadWrite() {
420 if (isSnapshotOnly()) {
421 throw new UnsupportedOperationException("Transaction " + getIdentifier() + " is a read-only snapshot");
425 final void recordSuccessfulRequest(final @NonNull TransactionRequest<?> req) {
426 successfulRequests.add(verifyNotNull(req));
429 final void recordFinishedRequest(final Response<?, ?> response) {
430 final Object last = successfulRequests.peekLast();
431 if (last instanceof IncrementSequence) {
432 ((IncrementSequence) last).incrementDelta();
434 successfulRequests.addLast(new IncrementSequence(response.getSequence()));
439 * Abort this transaction. This is invoked only for read-only transactions and will result in an explicit message
440 * being sent to the backend.
444 parent.abortTransaction(this);
446 sendRequest(abortRequest(), resp -> {
447 LOG.debug("Transaction {} abort completed with {}", getIdentifier(), resp);
452 final void abort(final VotingFuture<Empty> ret) {
456 if (t instanceof TransactionAbortSuccess) {
458 } else if (t instanceof RequestFailure) {
459 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
461 ret.voteNo(unhandledResponseException(t));
464 // This is a terminal request, hence we do not need to record it
465 LOG.debug("Transaction {} abort completed", this);
470 final void enqueueAbort(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
472 parent.abortTransaction(this);
474 enqueueRequest(abortRequest(), resp -> {
475 LOG.debug("Transaction {} abort completed with {}", getIdentifier(), resp);
476 // Purge will be sent by the predecessor's callback
477 if (callback != null) {
478 callback.accept(resp);
483 final void enqueueDoAbort(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
484 enqueueRequest(new TransactionAbortRequest(getIdentifier(), nextSequence(), localActor()), callback,
488 final void sendDoAbort(final Consumer<Response<?, ?>> callback) {
489 sendRequest(new TransactionAbortRequest(getIdentifier(), nextSequence(), localActor()), callback);
493 * Commit this transaction, possibly in a coordinated fashion.
495 * @param coordinated True if this transaction should be coordinated across multiple participants.
496 * @return Future completion
498 final ListenableFuture<Boolean> directCommit() {
502 // Precludes startReconnect() from interfering with the fast path
503 synchronized (this) {
504 if (STATE_UPDATER.compareAndSet(this, SEALED, FLUSHED)) {
505 final SettableFuture<Boolean> ret = SettableFuture.create();
506 sendRequest(verifyNotNull(commitRequest(false)), t -> {
507 if (t instanceof TransactionCommitSuccess) {
508 ret.set(Boolean.TRUE);
509 } else if (t instanceof RequestFailure) {
510 final Throwable cause = ((RequestFailure<?, ?>) t).getCause().unwrap();
511 if (cause instanceof ClosedTransactionException) {
512 // This is okay, as it indicates the transaction has been completed. It can happen
513 // when we lose connectivity with the backend after it has received the request.
514 ret.set(Boolean.TRUE);
516 ret.setException(cause);
519 ret.setException(unhandledResponseException(t));
522 // This is a terminal request, hence we do not need to record it
523 LOG.debug("Transaction {} directCommit completed", this);
531 // We have had some interference with successor injection, wait for it to complete and defer to the successor.
532 return awaitSuccessor().directCommit();
535 final void canCommit(final VotingFuture<?> ret) {
539 // Precludes startReconnect() from interfering with the fast path
540 synchronized (this) {
541 if (STATE_UPDATER.compareAndSet(this, SEALED, FLUSHED)) {
542 final TransactionRequest<?> req = verifyNotNull(commitRequest(true));
544 sendRequest(req, t -> {
545 if (t instanceof TransactionCanCommitSuccess) {
547 } else if (t instanceof RequestFailure) {
548 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
550 ret.voteNo(unhandledResponseException(t));
553 recordSuccessfulRequest(req);
554 LOG.debug("Transaction {} canCommit completed", this);
561 // We have had some interference with successor injection, wait for it to complete and defer to the successor.
562 awaitSuccessor().canCommit(ret);
565 private AbstractProxyTransaction awaitSuccessor() {
566 return getSuccessorState().await();
569 final void preCommit(final VotingFuture<?> ret) {
573 final TransactionRequest<?> req = new TransactionPreCommitRequest(getIdentifier(), nextSequence(),
575 sendRequest(req, t -> {
576 if (t instanceof TransactionPreCommitSuccess) {
578 } else if (t instanceof RequestFailure) {
579 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
581 ret.voteNo(unhandledResponseException(t));
584 onPreCommitComplete(req);
588 private void onPreCommitComplete(final TransactionRequest<?> req) {
590 * The backend has agreed that the transaction has entered PRE_COMMIT phase, meaning it will be committed
591 * to storage after the timeout completes.
593 * All state has been replicated to the backend, hence we do not need to keep it around. Retain only
594 * the precommit request, so we know which request to use for resync.
596 LOG.debug("Transaction {} preCommit completed, clearing successfulRequests", this);
597 successfulRequests.clear();
599 // TODO: this works, but can contain some useless state (like batched operations). Create an empty
600 // equivalent of this request and store that.
601 recordSuccessfulRequest(req);
604 final void doCommit(final VotingFuture<?> ret) {
608 sendRequest(new TransactionDoCommitRequest(getIdentifier(), nextSequence(), localActor()), t -> {
609 if (t instanceof TransactionCommitSuccess) {
611 } else if (t instanceof RequestFailure) {
612 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
614 ret.voteNo(unhandledResponseException(t));
617 LOG.debug("Transaction {} doCommit completed", this);
619 // Needed for ProxyHistory$Local data tree rebase points.
620 parent.completeTransaction(this);
626 private void enqueuePurge() {
630 final void enqueuePurge(final Consumer<Response<?, ?>> callback) {
631 // Purge request are dispatched internally, hence should not wait
632 enqueuePurge(callback, parent.currentTime());
635 final void enqueuePurge(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
636 LOG.debug("{}: initiating purge", this);
638 final State prev = state;
639 if (prev instanceof SuccessorState) {
640 ((SuccessorState) prev).setDone();
642 final boolean success = STATE_UPDATER.compareAndSet(this, prev, DONE);
644 LOG.warn("{}: moved from state {} while we were purging it", this, prev);
648 successfulRequests.clear();
650 enqueueRequest(new TransactionPurgeRequest(getIdentifier(), nextSequence(), localActor()), resp -> {
651 LOG.debug("{}: purge completed", this);
652 parent.purgeTransaction(this);
654 if (callback != null) {
655 callback.accept(resp);
660 // Called with the connection unlocked
661 final synchronized void startReconnect() {
662 // At this point canCommit/directCommit are blocked, we assert a new successor state, retrieving the previous
663 // state. This method is called with the queue still unlocked.
664 final SuccessorState nextState = new SuccessorState();
665 final State prevState = STATE_UPDATER.getAndSet(this, nextState);
667 LOG.debug("Start reconnect of proxy {} previous state {}", this, prevState);
668 verify(!(prevState instanceof SuccessorState), "Proxy %s duplicate reconnect attempt after %s", this,
671 // We have asserted a slow-path state, seal(), canCommit(), directCommit() are forced to slow paths, which will
672 // wait until we unblock nextState's latch before accessing state. Now we record prevState for later use and we
674 nextState.setPrevState(prevState);
677 // Called with the connection locked
678 final void replayMessages(final ProxyHistory successorHistory, final Iterable<ConnectionEntry> enqueuedEntries) {
679 final SuccessorState local = getSuccessorState();
680 final State prevState = local.getPrevState();
682 final AbstractProxyTransaction successor = successorHistory.createTransactionProxy(getIdentifier(),
683 isSnapshotOnly(), local.isDone());
684 LOG.debug("{} created successor {}", this, successor);
685 local.setSuccessor(successor);
687 // Replay successful requests first
688 if (!successfulRequests.isEmpty()) {
689 // We need to find a good timestamp to use for successful requests, as we do not want to time them out
690 // nor create timing inconsistencies in the queue -- requests are expected to be ordered by their enqueue
691 // time. We will pick the time of the first entry available. If there is none, we will just use current
692 // time, as all other requests will get enqueued afterwards.
693 final ConnectionEntry firstInQueue = Iterables.getFirst(enqueuedEntries, null);
694 final long now = firstInQueue != null ? firstInQueue.getEnqueuedTicks() : parent.currentTime();
696 for (Object obj : successfulRequests) {
697 if (obj instanceof TransactionRequest) {
698 LOG.debug("Forwarding successful request {} to successor {}", obj, successor);
699 successor.doReplayRequest((TransactionRequest<?>) obj, resp -> { /*NOOP*/ }, now);
701 verify(obj instanceof IncrementSequence);
702 final IncrementSequence increment = (IncrementSequence) obj;
703 successor.doReplayRequest(new IncrementTransactionSequenceRequest(getIdentifier(),
704 increment.getSequence(), localActor(), isSnapshotOnly(),
705 increment.getDelta()), resp -> { /*NOOP*/ }, now);
706 LOG.debug("Incrementing sequence {} to successor {}", obj, successor);
709 LOG.debug("{} replayed {} successful requests", getIdentifier(), successfulRequests.size());
710 successfulRequests.clear();
713 // Now replay whatever is in the connection
714 final Iterator<ConnectionEntry> it = enqueuedEntries.iterator();
715 while (it.hasNext()) {
716 final ConnectionEntry e = it.next();
717 final Request<?, ?> req = e.getRequest();
719 if (getIdentifier().equals(req.getTarget())) {
720 verify(req instanceof TransactionRequest, "Unhandled request %s", req);
721 LOG.debug("Replaying queued request {} to successor {}", req, successor);
722 successor.doReplayRequest((TransactionRequest<?>) req, e.getCallback(), e.getEnqueuedTicks());
728 * Check the state at which we have started the reconnect attempt. State transitions triggered while we were
729 * reconnecting have been forced to slow paths, which will be unlocked once we unblock the state latch
730 * at the end of this method.
732 if (SEALED.equals(prevState)) {
733 LOG.debug("Proxy {} reconnected while being sealed, propagating state to successor {}", this, successor);
734 final long enqueuedTicks = parent.currentTime();
735 final Optional<ModifyTransactionRequest> optState = flushState();
736 if (optState.isPresent()) {
737 successor.handleReplayedRemoteRequest(optState.get(), null, enqueuedTicks);
739 if (successor.markSealed()) {
740 successor.sealAndSend(OptionalLong.of(enqueuedTicks));
746 * Invoked from {@link #replayMessages(AbstractProxyTransaction, Iterable)} to have successor adopt an in-flight
750 * Note: this method is invoked by the predecessor on the successor.
752 * @param request Request which needs to be forwarded
753 * @param callback Callback to be invoked once the request completes
754 * @param enqueuedTicks ticker-based time stamp when the request was enqueued
756 private void doReplayRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
757 final long enqueuedTicks) {
758 if (request instanceof AbstractLocalTransactionRequest) {
759 handleReplayedLocalRequest((AbstractLocalTransactionRequest<?>) request, callback, enqueuedTicks);
761 handleReplayedRemoteRequest(request, callback, enqueuedTicks);
765 // Called with the connection locked
766 final void finishReconnect() {
767 final SuccessorState local = getSuccessorState();
768 LOG.debug("Finishing reconnect of proxy {}", this);
770 // All done, release the latch, unblocking seal() and canCommit() slow paths
775 * Invoked from a retired connection for requests which have been in-flight and need to be re-adjusted
776 * and forwarded to the successor connection.
778 * @param request Request to be forwarded
779 * @param callback Original callback
781 final void forwardRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
782 forwardToSuccessor(getSuccessorState().getSuccessor(), request, callback);
785 final void forwardToSuccessor(final AbstractProxyTransaction successor, final TransactionRequest<?> request,
786 final Consumer<Response<?, ?>> callback) {
787 if (successor instanceof LocalProxyTransaction) {
788 forwardToLocal((LocalProxyTransaction)successor, request, callback);
789 } else if (successor instanceof RemoteProxyTransaction) {
790 forwardToRemote((RemoteProxyTransaction)successor, request, callback);
792 throw new IllegalStateException("Unhandled successor " + successor);
796 final void replayRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
797 final long enqueuedTicks) {
798 getSuccessorState().getSuccessor().doReplayRequest(request, callback, enqueuedTicks);
801 abstract boolean isSnapshotOnly();
803 abstract void doDelete(YangInstanceIdentifier path);
805 abstract void doMerge(YangInstanceIdentifier path, NormalizedNode data);
807 abstract void doWrite(YangInstanceIdentifier path, NormalizedNode data);
809 abstract FluentFuture<Boolean> doExists(YangInstanceIdentifier path);
811 abstract FluentFuture<Optional<NormalizedNode>> doRead(YangInstanceIdentifier path);
814 abstract Optional<ModifyTransactionRequest> flushState();
816 abstract TransactionRequest<?> abortRequest();
818 abstract TransactionRequest<?> commitRequest(boolean coordinated);
821 * Replay a request originating in this proxy to a successor remote proxy.
823 abstract void forwardToRemote(RemoteProxyTransaction successor, TransactionRequest<?> request,
824 Consumer<Response<?, ?>> callback);
827 * Replay a request originating in this proxy to a successor local proxy.
829 abstract void forwardToLocal(LocalProxyTransaction successor, TransactionRequest<?> request,
830 Consumer<Response<?, ?>> callback);
833 * Invoked from {@link LocalProxyTransaction} when it replays its successful requests to its successor.
836 * Note: this method is invoked by the predecessor on the successor.
838 * @param request Request which needs to be forwarded
839 * @param callback Callback to be invoked once the request completes
840 * @param enqueuedTicks Time stamp to use for enqueue time
842 abstract void handleReplayedLocalRequest(AbstractLocalTransactionRequest<?> request,
843 @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
846 * Invoked from {@link RemoteProxyTransaction} when it replays its successful requests to its successor.
849 * Note: this method is invoked by the predecessor on the successor.
851 * @param request Request which needs to be forwarded
852 * @param callback Callback to be invoked once the request completes
853 * @param enqueuedTicks Time stamp to use for enqueue time
855 abstract void handleReplayedRemoteRequest(TransactionRequest<?> request,
856 @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
858 private static IllegalStateException unhandledResponseException(final Response<?, ?> resp) {
859 return new IllegalStateException("Unhandled response " + resp.getClass());
863 public final String toString() {
864 return MoreObjects.toStringHelper(this).add("identifier", getIdentifier()).add("state", state).toString();