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 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.Throwables;
15 import com.google.common.base.Verify;
16 import com.google.common.collect.Iterables;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.SettableFuture;
20 import java.util.ArrayDeque;
21 import java.util.Deque;
22 import java.util.Iterator;
23 import java.util.concurrent.CountDownLatch;
24 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
25 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
26 import java.util.function.Consumer;
27 import javax.annotation.Nonnull;
28 import javax.annotation.Nullable;
29 import javax.annotation.concurrent.GuardedBy;
30 import javax.annotation.concurrent.NotThreadSafe;
31 import org.opendaylight.controller.cluster.access.client.ConnectionEntry;
32 import org.opendaylight.controller.cluster.access.commands.AbstractLocalTransactionRequest;
33 import org.opendaylight.controller.cluster.access.commands.ClosedTransactionException;
34 import org.opendaylight.controller.cluster.access.commands.IncrementTransactionSequenceRequest;
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;
56 * Class translating transaction operations towards a particular backend shard.
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.
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.
66 * @author Robert Varga
68 abstract class AbstractProxyTransaction implements Identifiable<TransactionIdentifier> {
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.
74 private static final class IncrementSequence {
75 private final long sequence;
76 private long delta = 0;
78 IncrementSequence(final long sequence) {
79 this.sequence = sequence;
90 void incrementDelta() {
96 * Base class for representing logical state of this proxy. See individual instantiations and {@link SuccessorState}
99 private static class State {
100 private final String string;
102 State(final String string) {
103 this.string = Preconditions.checkNotNull(string);
107 public final String toString() {
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
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.
123 private static class SuccessorState extends State {
124 private final CountDownLatch latch = new CountDownLatch(1);
125 private AbstractProxyTransaction successor;
126 private State prevState;
129 private boolean done;
135 // Synchronize with succession process and return the successor
136 AbstractProxyTransaction await() {
139 } catch (InterruptedException e) {
140 LOG.warn("Interrupted while waiting for latch of {}", successor);
141 throw Throwables.propagate(e);
150 State getPrevState() {
151 return Verify.verifyNotNull(prevState, "Attempted to access previous state, which was not set");
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);
162 // To be called from safe contexts, where successor is known to be completed
163 AbstractProxyTransaction getSuccessor() {
164 return Verify.verifyNotNull(successor);
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);
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");
189 * Transaction has been open and is being actively worked on.
191 private static final State OPEN = new State("OPEN");
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.
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.
202 private static final State SEALED = new State("SEALED");
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.
210 * Transition to this state indicates we have all input from the user we need to initiate the correct commit
213 private static final State FLUSHED = new State("FLUSHED");
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.
221 private static final State DONE = new State("DONE");
223 // Touched from client actor thread only
224 private final Deque<Object> successfulRequests = new ArrayDeque<>();
225 private final ProxyHistory parent;
227 // Accessed from user thread only, which may not access this object concurrently
228 private long sequence;
231 * Atomic state-keeping is required to synchronize the process of propagating completed transaction state towards
232 * the backend -- which may include a successor.
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.
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.
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.
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.
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).
254 private volatile int sealed;
255 private volatile State state;
257 AbstractProxyTransaction(final ProxyHistory parent, final boolean isDone) {
258 this.parent = Preconditions.checkNotNull(parent);
261 // DONE implies previous seal operation completed
268 final void executeInActor(final Runnable command) {
269 parent.context().executeInActor(behavior -> {
275 final ActorRef localActor() {
276 return parent.localActor();
279 final void incrementSequence(final long delta) {
281 LOG.debug("Transaction {} incremented sequence to {}", this, sequence);
284 final long nextSequence() {
285 final long ret = sequence++;
286 LOG.debug("Transaction {} allocated sequence {}", this, ret);
290 final void delete(final YangInstanceIdentifier path) {
296 final void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
302 final void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
308 final CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
310 return doExists(path);
313 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
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);
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);
330 * Seal this transaction before it is either committed or aborted. This method should only be invoked from
331 * application thread.
334 // Transition user-visible state first
335 final boolean success = markSealed();
336 Preconditions.checkState(success, "Proxy %s was already sealed", getIdentifier());
338 if (!sealAndSend(Optional.absent())) {
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.
347 private void sealSuccessor() {
348 // Slow path: wait for the successor to complete
349 final AbstractProxyTransaction successor = awaitSuccessor();
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 flushState(successor);
355 successor.predecessorSealed();
358 private void predecessorSealed() {
359 if (markSealed() && !sealAndSend(Optional.absent())) {
365 parent.onTransactionSealed(this);
366 final boolean success = STATE_UPDATER.compareAndSet(this, OPEN, SEALED);
367 Verify.verify(success, "Attempted to replay seal on {}", this);
371 * Seal this transaction and potentially send it out towards the backend. If this method reports false, the caller
372 * needs to deal with propagating the seal operation towards the successor.
374 * @param enqueuedTicks Enqueue ticks when this is invoked from replay path.
375 * @return True if seal operation was successful, false if this proxy has a successor.
377 boolean sealAndSend(final Optional<Long> enqueuedTicks) {
378 parent.onTransactionSealed(this);
380 // Transition internal state to sealed and detect presence of a successor
381 return STATE_UPDATER.compareAndSet(this, OPEN, SEALED);
385 * Mark this proxy as having been sealed.
387 * @return True if this call has transitioned to sealed state.
389 final boolean markSealed() {
390 return SEALED_UPDATER.compareAndSet(this, 0, 1);
393 private void checkNotSealed() {
394 Preconditions.checkState(sealed == 0, "Transaction %s has already been sealed", getIdentifier());
397 private void checkSealed() {
398 Preconditions.checkState(sealed != 0, "Transaction %s has not been sealed yet", getIdentifier());
401 private SuccessorState getSuccessorState() {
402 final State local = state;
403 Verify.verify(local instanceof SuccessorState, "State %s has unexpected class", local);
404 return (SuccessorState) local;
407 private void checkReadWrite() {
408 if (isSnapshotOnly()) {
409 throw new UnsupportedOperationException("Transaction " + getIdentifier() + " is a read-only snapshot");
413 final void recordSuccessfulRequest(final @Nonnull TransactionRequest<?> req) {
414 successfulRequests.add(Verify.verifyNotNull(req));
417 final void recordFinishedRequest(final Response<?, ?> response) {
418 final Object last = successfulRequests.peekLast();
419 if (last instanceof IncrementSequence) {
420 ((IncrementSequence) last).incrementDelta();
422 successfulRequests.addLast(new IncrementSequence(response.getSequence()));
427 * Abort this transaction. This is invoked only for read-only transactions and will result in an explicit message
428 * being sent to the backend.
432 parent.abortTransaction(this);
434 sendRequest(abortRequest(), resp -> {
435 LOG.debug("Transaction {} abort completed with {}", getIdentifier(), resp);
440 final void abort(final VotingFuture<Void> ret) {
444 if (t instanceof TransactionAbortSuccess) {
446 } else if (t instanceof RequestFailure) {
447 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
449 ret.voteNo(new IllegalStateException("Unhandled response " + t.getClass()));
452 // This is a terminal request, hence we do not need to record it
453 LOG.debug("Transaction {} abort completed", this);
458 final void enqueueAbort(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
460 parent.abortTransaction(this);
462 enqueueRequest(abortRequest(), resp -> {
463 LOG.debug("Transaction {} abort completed with {}", getIdentifier(), resp);
464 // Purge will be sent by the predecessor's callback
465 if (callback != null) {
466 callback.accept(resp);
471 final void enqueueDoAbort(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
472 enqueueRequest(new TransactionAbortRequest(getIdentifier(), nextSequence(), localActor()), callback,
476 final void sendDoAbort(final Consumer<Response<?, ?>> callback) {
477 sendRequest(new TransactionAbortRequest(getIdentifier(), nextSequence(), localActor()), callback);
481 * Commit this transaction, possibly in a coordinated fashion.
483 * @param coordinated True if this transaction should be coordinated across multiple participants.
484 * @return Future completion
486 final ListenableFuture<Boolean> directCommit() {
490 // Precludes startReconnect() from interfering with the fast path
491 synchronized (this) {
492 if (STATE_UPDATER.compareAndSet(this, SEALED, FLUSHED)) {
493 final SettableFuture<Boolean> ret = SettableFuture.create();
494 sendRequest(Verify.verifyNotNull(commitRequest(false)), t -> {
495 if (t instanceof TransactionCommitSuccess) {
496 ret.set(Boolean.TRUE);
497 } else if (t instanceof RequestFailure) {
498 final Throwable cause = ((RequestFailure<?, ?>) t).getCause().unwrap();
499 if (cause instanceof ClosedTransactionException) {
500 // This is okay, as it indicates the transaction has been completed. It can happen
501 // when we lose connectivity with the backend after it has received the request.
502 ret.set(Boolean.TRUE);
504 ret.setException(cause);
507 ret.setException(new IllegalStateException("Unhandled response " + t.getClass()));
510 // This is a terminal request, hence we do not need to record it
511 LOG.debug("Transaction {} directCommit completed", this);
519 // We have had some interference with successor injection, wait for it to complete and defer to the successor.
520 return awaitSuccessor().directCommit();
523 final void canCommit(final VotingFuture<?> ret) {
527 // Precludes startReconnect() from interfering with the fast path
528 synchronized (this) {
529 if (STATE_UPDATER.compareAndSet(this, SEALED, FLUSHED)) {
530 final TransactionRequest<?> req = Verify.verifyNotNull(commitRequest(true));
532 sendRequest(req, t -> {
533 if (t instanceof TransactionCanCommitSuccess) {
535 } else if (t instanceof RequestFailure) {
536 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
538 ret.voteNo(new IllegalStateException("Unhandled response " + t.getClass()));
541 recordSuccessfulRequest(req);
542 LOG.debug("Transaction {} canCommit completed", this);
549 // We have had some interference with successor injection, wait for it to complete and defer to the successor.
550 awaitSuccessor().canCommit(ret);
553 private AbstractProxyTransaction awaitSuccessor() {
554 return getSuccessorState().await();
557 final void preCommit(final VotingFuture<?> ret) {
561 final TransactionRequest<?> req = new TransactionPreCommitRequest(getIdentifier(), nextSequence(),
563 sendRequest(req, t -> {
564 if (t instanceof TransactionPreCommitSuccess) {
566 } else if (t instanceof RequestFailure) {
567 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
569 ret.voteNo(new IllegalStateException("Unhandled response " + t.getClass()));
572 onPreCommitComplete(req);
576 private void onPreCommitComplete(final TransactionRequest<?> req) {
578 * The backend has agreed that the transaction has entered PRE_COMMIT phase, meaning it will be committed
579 * to storage after the timeout completes.
581 * All state has been replicated to the backend, hence we do not need to keep it around. Retain only
582 * the precommit request, so we know which request to use for resync.
584 LOG.debug("Transaction {} preCommit completed, clearing successfulRequests", this);
585 successfulRequests.clear();
587 // TODO: this works, but can contain some useless state (like batched operations). Create an empty
588 // equivalent of this request and store that.
589 recordSuccessfulRequest(req);
592 final void doCommit(final VotingFuture<?> ret) {
596 sendRequest(new TransactionDoCommitRequest(getIdentifier(), nextSequence(), localActor()), t -> {
597 if (t instanceof TransactionCommitSuccess) {
599 } else if (t instanceof RequestFailure) {
600 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
602 ret.voteNo(new IllegalStateException("Unhandled response " + t.getClass()));
605 LOG.debug("Transaction {} doCommit completed", this);
607 // Needed for ProxyHistory$Local data tree rebase points.
608 parent.completeTransaction(this);
614 private void enqueuePurge() {
618 final void enqueuePurge(final Consumer<Response<?, ?>> callback) {
619 // Purge request are dispatched internally, hence should not wait
620 enqueuePurge(callback, parent.currentTime());
623 final void enqueuePurge(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
624 LOG.debug("{}: initiating purge", this);
626 final State prev = state;
627 if (prev instanceof SuccessorState) {
628 ((SuccessorState) prev).setDone();
630 final boolean success = STATE_UPDATER.compareAndSet(this, prev, DONE);
632 LOG.warn("{}: moved from state {} while we were purging it", this, prev);
636 successfulRequests.clear();
638 enqueueRequest(new TransactionPurgeRequest(getIdentifier(), nextSequence(), localActor()), resp -> {
639 LOG.debug("{}: purge completed", this);
640 parent.purgeTransaction(this);
642 if (callback != null) {
643 callback.accept(resp);
648 // Called with the connection unlocked
649 final synchronized void startReconnect() {
650 // At this point canCommit/directCommit are blocked, we assert a new successor state, retrieving the previous
651 // state. This method is called with the queue still unlocked.
652 final SuccessorState nextState = new SuccessorState();
653 final State prevState = STATE_UPDATER.getAndSet(this, nextState);
655 LOG.debug("Start reconnect of proxy {} previous state {}", this, prevState);
656 Verify.verify(!(prevState instanceof SuccessorState), "Proxy %s duplicate reconnect attempt after %s", this,
659 // We have asserted a slow-path state, seal(), canCommit(), directCommit() are forced to slow paths, which will
660 // wait until we unblock nextState's latch before accessing state. Now we record prevState for later use and we
662 nextState.setPrevState(prevState);
665 // Called with the connection locked
666 final void replayMessages(final ProxyHistory successorHistory, final Iterable<ConnectionEntry> enqueuedEntries) {
667 final SuccessorState local = getSuccessorState();
668 final State prevState = local.getPrevState();
670 final AbstractProxyTransaction successor = successorHistory.createTransactionProxy(getIdentifier(),
671 isSnapshotOnly(), local.isDone());
672 LOG.debug("{} created successor {}", this, successor);
673 local.setSuccessor(successor);
675 // Replay successful requests first
676 if (!successfulRequests.isEmpty()) {
677 // We need to find a good timestamp to use for successful requests, as we do not want to time them out
678 // nor create timing inconsistencies in the queue -- requests are expected to be ordered by their enqueue
679 // time. We will pick the time of the first entry available. If there is none, we will just use current
680 // time, as all other requests will get enqueued afterwards.
681 final ConnectionEntry firstInQueue = Iterables.getFirst(enqueuedEntries, null);
682 final long now = firstInQueue != null ? firstInQueue.getEnqueuedTicks() : parent.currentTime();
684 for (Object obj : successfulRequests) {
685 if (obj instanceof TransactionRequest) {
686 LOG.debug("Forwarding successful request {} to successor {}", obj, successor);
687 successor.doReplayRequest((TransactionRequest<?>) obj, resp -> { }, now);
689 Verify.verify(obj instanceof IncrementSequence);
690 final IncrementSequence increment = (IncrementSequence) obj;
691 successor.doReplayRequest(new IncrementTransactionSequenceRequest(getIdentifier(),
692 increment.getSequence(), localActor(), isSnapshotOnly(), increment.getDelta()), resp -> { },
694 LOG.debug("Incrementing sequence {} to successor {}", obj, successor);
697 LOG.debug("{} replayed {} successful requests", getIdentifier(), successfulRequests.size());
698 successfulRequests.clear();
701 // Now replay whatever is in the connection
702 final Iterator<ConnectionEntry> it = enqueuedEntries.iterator();
703 while (it.hasNext()) {
704 final ConnectionEntry e = it.next();
705 final Request<?, ?> req = e.getRequest();
707 if (getIdentifier().equals(req.getTarget())) {
708 Verify.verify(req instanceof TransactionRequest, "Unhandled request %s", req);
709 LOG.debug("Replaying queued request {} to successor {}", req, successor);
710 successor.doReplayRequest((TransactionRequest<?>) req, e.getCallback(), e.getEnqueuedTicks());
716 * Check the state at which we have started the reconnect attempt. State transitions triggered while we were
717 * reconnecting have been forced to slow paths, which will be unlocked once we unblock the state latch
718 * at the end of this method.
720 if (SEALED.equals(prevState)) {
721 LOG.debug("Proxy {} reconnected while being sealed, propagating state to successor {}", this, successor);
722 flushState(successor);
723 if (successor.markSealed()) {
724 successor.sealAndSend(Optional.of(parent.currentTime()));
730 * Invoked from {@link #replayMessages(AbstractProxyTransaction, Iterable)} to have successor adopt an in-flight
734 * Note: this method is invoked by the predecessor on the successor.
736 * @param request Request which needs to be forwarded
737 * @param callback Callback to be invoked once the request completes
738 * @param enqueuedTicks ticker-based time stamp when the request was enqueued
740 private void doReplayRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
741 final long enqueuedTicks) {
742 if (request instanceof AbstractLocalTransactionRequest) {
743 handleReplayedLocalRequest((AbstractLocalTransactionRequest<?>) request, callback, enqueuedTicks);
745 handleReplayedRemoteRequest(request, callback, enqueuedTicks);
749 // Called with the connection locked
750 final void finishReconnect() {
751 final SuccessorState local = getSuccessorState();
752 LOG.debug("Finishing reconnect of proxy {}", this);
754 // All done, release the latch, unblocking seal() and canCommit() slow paths
759 * Invoked from a retired connection for requests which have been in-flight and need to be re-adjusted
760 * and forwarded to the successor connection.
762 * @param request Request to be forwarded
763 * @param callback Original callback
765 final void forwardRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
766 forwardToSuccessor(getSuccessorState().getSuccessor(), request, callback);
769 final void forwardToSuccessor(final AbstractProxyTransaction successor, final TransactionRequest<?> request,
770 final Consumer<Response<?, ?>> callback) {
771 if (successor instanceof LocalProxyTransaction) {
772 forwardToLocal((LocalProxyTransaction)successor, request, callback);
773 } else if (successor instanceof RemoteProxyTransaction) {
774 forwardToRemote((RemoteProxyTransaction)successor, request, callback);
776 throw new IllegalStateException("Unhandled successor " + successor);
780 final void replayRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
781 final long enqueuedTicks) {
782 getSuccessorState().getSuccessor().doReplayRequest(request, callback, enqueuedTicks);
785 abstract boolean isSnapshotOnly();
787 abstract void doDelete(YangInstanceIdentifier path);
789 abstract void doMerge(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
791 abstract void doWrite(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
793 abstract CheckedFuture<Boolean, ReadFailedException> doExists(YangInstanceIdentifier path);
795 abstract CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> doRead(YangInstanceIdentifier path);
798 abstract void flushState(AbstractProxyTransaction successor);
800 abstract TransactionRequest<?> abortRequest();
802 abstract TransactionRequest<?> commitRequest(boolean coordinated);
805 * Replay a request originating in this proxy to a successor remote proxy.
807 abstract void forwardToRemote(RemoteProxyTransaction successor, TransactionRequest<?> request,
808 Consumer<Response<?, ?>> callback);
811 * Replay a request originating in this proxy to a successor local proxy.
813 abstract void forwardToLocal(LocalProxyTransaction successor, TransactionRequest<?> request,
814 Consumer<Response<?, ?>> callback);
817 * Invoked from {@link LocalProxyTransaction} when it replays its successful requests to its successor.
820 * Note: this method is invoked by the predecessor on the successor.
822 * @param request Request which needs to be forwarded
823 * @param callback Callback to be invoked once the request completes
824 * @param enqueuedTicks Time stamp to use for enqueue time
826 abstract void handleReplayedLocalRequest(AbstractLocalTransactionRequest<?> request,
827 @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
830 * Invoked from {@link RemoteProxyTransaction} when it replays its successful requests to its successor.
833 * Note: this method is invoked by the predecessor on the successor.
835 * @param request Request which needs to be forwarded
836 * @param callback Callback to be invoked once the request completes
837 * @param enqueuedTicks Time stamp to use for enqueue time
839 abstract void handleReplayedRemoteRequest(TransactionRequest<?> request,
840 @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
843 public final String toString() {
844 return MoreObjects.toStringHelper(this).add("identifier", getIdentifier()).add("state", state).toString();