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.IncrementTransactionSequenceRequest;
34 import org.opendaylight.controller.cluster.access.commands.TransactionAbortRequest;
35 import org.opendaylight.controller.cluster.access.commands.TransactionAbortSuccess;
36 import org.opendaylight.controller.cluster.access.commands.TransactionCanCommitSuccess;
37 import org.opendaylight.controller.cluster.access.commands.TransactionCommitSuccess;
38 import org.opendaylight.controller.cluster.access.commands.TransactionDoCommitRequest;
39 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitRequest;
40 import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitSuccess;
41 import org.opendaylight.controller.cluster.access.commands.TransactionPurgeRequest;
42 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
43 import org.opendaylight.controller.cluster.access.concepts.Request;
44 import org.opendaylight.controller.cluster.access.concepts.RequestFailure;
45 import org.opendaylight.controller.cluster.access.concepts.Response;
46 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
47 import org.opendaylight.mdsal.common.api.ReadFailedException;
48 import org.opendaylight.yangtools.concepts.Identifiable;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
55 * Class translating transaction operations towards a particular backend shard.
58 * This class is not safe to access from multiple application threads, as is usual for transactions. Internal state
59 * transitions coming from interactions with backend are expected to be thread-safe.
62 * This class interacts with the queueing mechanism in ClientActorBehavior, hence once we arrive at a decision
63 * to use either a local or remote implementation, we are stuck with it. We can re-evaluate on the next transaction.
65 * @author Robert Varga
67 abstract class AbstractProxyTransaction implements Identifiable<TransactionIdentifier> {
69 * Marker object used instead of read-type of requests, which are satisfied only once. This has a lower footprint
70 * and allows compressing multiple requests into a single entry.
73 private static final class IncrementSequence {
74 private final long sequence;
75 private long delta = 0;
77 IncrementSequence(final long sequence) {
78 this.sequence = sequence;
89 void incrementDelta() {
94 // Generic state base class. Direct instances are used for fast paths, sub-class is used for successor transitions
95 private static class State {
96 private final String string;
98 State(final String string) {
99 this.string = Preconditions.checkNotNull(string);
103 public final String toString() {
108 // State class used when a successor has interfered. Contains coordinator latch, the successor and previous state
109 private static final class SuccessorState extends State {
110 private final CountDownLatch latch = new CountDownLatch(1);
111 private AbstractProxyTransaction successor;
112 private State prevState;
118 // Synchronize with succession process and return the successor
119 AbstractProxyTransaction await() {
122 } catch (InterruptedException e) {
123 LOG.warn("Interrupted while waiting for latch of {}", successor);
124 throw Throwables.propagate(e);
133 State getPrevState() {
137 void setPrevState(final State prevState) {
138 Verify.verify(this.prevState == null);
139 this.prevState = Preconditions.checkNotNull(prevState);
142 // To be called from safe contexts, where successor is known to be completed
143 AbstractProxyTransaction getSuccessor() {
144 return Verify.verifyNotNull(successor);
147 void setSuccessor(final AbstractProxyTransaction successor) {
148 Verify.verify(this.successor == null);
149 this.successor = Preconditions.checkNotNull(successor);
153 private static final Logger LOG = LoggerFactory.getLogger(AbstractProxyTransaction.class);
154 private static final AtomicIntegerFieldUpdater<AbstractProxyTransaction> SEALED_UPDATER =
155 AtomicIntegerFieldUpdater.newUpdater(AbstractProxyTransaction.class, "sealed");
156 private static final AtomicReferenceFieldUpdater<AbstractProxyTransaction, State> STATE_UPDATER =
157 AtomicReferenceFieldUpdater.newUpdater(AbstractProxyTransaction.class, State.class, "state");
158 private static final State OPEN = new State("open");
159 private static final State SEALED = new State("sealed");
160 private static final State FLUSHED = new State("flushed");
162 // Touched from client actor thread only
163 private final Deque<Object> successfulRequests = new ArrayDeque<>();
164 private final ProxyHistory parent;
166 // Accessed from user thread only, which may not access this object concurrently
167 private long sequence;
170 * Atomic state-keeping is required to synchronize the process of propagating completed transaction state towards
171 * the backend -- which may include a successor.
173 * Successor, unlike {@link AbstractProxyTransaction#seal()} is triggered from the client actor thread, which means
174 * the successor placement needs to be atomic with regard to the application thread.
176 * In the common case, the application thread performs performs the seal operations and then "immediately" sends
177 * the corresponding message. The uncommon case is when the seal and send operations race with a connect completion
178 * or timeout, when a successor is injected.
180 * This leaves the problem of needing to completely transferring state just after all queued messages are replayed
181 * after a successor was injected, so that it can be properly sealed if we are racing. Further complication comes
182 * from lock ordering, where the successor injection works with a locked queue and locks proxy objects -- leading
183 * to a potential AB-BA deadlock in case of a naive implementation.
185 * For tracking user-visible state we use a single volatile int, which is flipped atomically from 0 to 1 exactly
186 * once in {@link AbstractProxyTransaction#seal()}. That keeps common operations fast, as they need to perform
187 * only a single volatile read to assert state correctness.
189 * For synchronizing client actor (successor-injecting) and user (commit-driving) thread, we keep a separate state
190 * variable. It uses pre-allocated objects for fast paths (i.e. no successor present) and a per-transition object
191 * for slow paths (when successor is injected/present).
193 private volatile int sealed = 0;
194 private volatile State state = OPEN;
196 AbstractProxyTransaction(final ProxyHistory parent) {
197 this.parent = Preconditions.checkNotNull(parent);
200 final ActorRef localActor() {
201 return parent.localActor();
204 final void incrementSequence(final long delta) {
206 LOG.debug("Transaction {} incremented sequence to {}", this, sequence);
209 final long nextSequence() {
210 final long ret = sequence++;
211 LOG.debug("Transaction {} allocated sequence {}", this, ret);
215 final void delete(final YangInstanceIdentifier path) {
221 final void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
227 final void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
233 final CheckedFuture<Boolean, ReadFailedException> exists(final YangInstanceIdentifier path) {
235 return doExists(path);
238 final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final YangInstanceIdentifier path) {
243 final void enqueueRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
244 final long enqueuedTicks) {
245 LOG.debug("Transaction proxy {} enqueing request {} callback {}", this, request, callback);
246 parent.enqueueRequest(request, callback, enqueuedTicks);
249 final void sendRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
250 LOG.debug("Transaction proxy {} sending request {} callback {}", this, request, callback);
251 parent.sendRequest(request, callback);
255 * Seal this transaction before it is either committed or aborted.
258 // Transition user-visible state first
259 final boolean success = SEALED_UPDATER.compareAndSet(this, 0, 1);
260 Preconditions.checkState(success, "Proxy %s was already sealed", getIdentifier());
264 final void ensureSealed() {
265 if (SEALED_UPDATER.compareAndSet(this, 0, 1)) {
270 private void internalSeal() {
272 parent.onTransactionSealed(this);
274 // Now deal with state transfer, which can occur via successor or a follow-up canCommit() or directCommit().
275 if (!STATE_UPDATER.compareAndSet(this, OPEN, SEALED)) {
276 // Slow path: wait for the successor to complete
277 final AbstractProxyTransaction successor = awaitSuccessor();
279 // At this point the successor has completed transition and is possibly visible by the user thread, which is
280 // still stuck here. The successor has not seen final part of our state, nor the fact it is sealed.
281 // Propagate state and seal the successor.
282 flushState(successor);
283 successor.ensureSealed();
287 private void checkNotSealed() {
288 Preconditions.checkState(sealed == 0, "Transaction %s has already been sealed", getIdentifier());
291 private void checkSealed() {
292 Preconditions.checkState(sealed != 0, "Transaction %s has not been sealed yet", getIdentifier());
295 private SuccessorState getSuccessorState() {
296 final State local = state;
297 Verify.verify(local instanceof SuccessorState, "State %s has unexpected class", local);
298 return (SuccessorState) local;
301 private void checkReadWrite() {
302 if (isSnapshotOnly()) {
303 throw new UnsupportedOperationException("Transaction " + getIdentifier() + " is a read-only snapshot");
307 final void recordSuccessfulRequest(final @Nonnull TransactionRequest<?> req) {
308 successfulRequests.add(Verify.verifyNotNull(req));
311 final void recordFinishedRequest(final Response<?, ?> response) {
312 final Object last = successfulRequests.peekLast();
313 if (last instanceof IncrementSequence) {
314 ((IncrementSequence) last).incrementDelta();
316 successfulRequests.addLast(new IncrementSequence(response.getSequence()));
321 * Abort this transaction. This is invoked only for read-only transactions and will result in an explicit message
322 * being sent to the backend.
327 parent.abortTransaction(this);
330 final void abort(final VotingFuture<Void> ret) {
334 if (t instanceof TransactionAbortSuccess) {
336 } else if (t instanceof RequestFailure) {
337 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
339 ret.voteNo(new IllegalStateException("Unhandled response " + t.getClass()));
342 // This is a terminal request, hence we do not need to record it
343 LOG.debug("Transaction {} abort completed", this);
348 final void enqueueAbort(final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
349 enqueueRequest(new TransactionAbortRequest(getIdentifier(), nextSequence(), localActor()), callback,
353 final void sendAbort(final Consumer<Response<?, ?>> callback) {
354 sendRequest(new TransactionAbortRequest(getIdentifier(), nextSequence(), localActor()), callback);
358 * Commit this transaction, possibly in a coordinated fashion.
360 * @param coordinated True if this transaction should be coordinated across multiple participants.
361 * @return Future completion
363 final ListenableFuture<Boolean> directCommit() {
367 // Precludes startReconnect() from interfering with the fast path
368 synchronized (this) {
369 if (STATE_UPDATER.compareAndSet(this, SEALED, FLUSHED)) {
370 final SettableFuture<Boolean> ret = SettableFuture.create();
371 sendRequest(Verify.verifyNotNull(commitRequest(false)), t -> {
372 if (t instanceof TransactionCommitSuccess) {
373 ret.set(Boolean.TRUE);
374 } else if (t instanceof RequestFailure) {
375 ret.setException(((RequestFailure<?, ?>) t).getCause().unwrap());
377 ret.setException(new IllegalStateException("Unhandled response " + t.getClass()));
380 // This is a terminal request, hence we do not need to record it
381 LOG.debug("Transaction {} directCommit completed", this);
389 // We have had some interference with successor injection, wait for it to complete and defer to the successor.
390 return awaitSuccessor().directCommit();
393 final void canCommit(final VotingFuture<?> ret) {
397 // Precludes startReconnect() from interfering with the fast path
398 synchronized (this) {
399 if (STATE_UPDATER.compareAndSet(this, SEALED, FLUSHED)) {
400 final TransactionRequest<?> req = Verify.verifyNotNull(commitRequest(true));
402 sendRequest(req, t -> {
403 if (t instanceof TransactionCanCommitSuccess) {
405 } else if (t instanceof RequestFailure) {
406 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
408 ret.voteNo(new IllegalStateException("Unhandled response " + t.getClass()));
411 recordSuccessfulRequest(req);
412 LOG.debug("Transaction {} canCommit completed", this);
419 // We have had some interference with successor injection, wait for it to complete and defer to the successor.
420 awaitSuccessor().canCommit(ret);
423 private AbstractProxyTransaction awaitSuccessor() {
424 return getSuccessorState().await();
427 final void preCommit(final VotingFuture<?> ret) {
431 final TransactionRequest<?> req = new TransactionPreCommitRequest(getIdentifier(), nextSequence(),
433 sendRequest(req, t -> {
434 if (t instanceof TransactionPreCommitSuccess) {
436 } else if (t instanceof RequestFailure) {
437 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
439 ret.voteNo(new IllegalStateException("Unhandled response " + t.getClass()));
442 onPreCommitComplete(req);
446 private void onPreCommitComplete(final TransactionRequest<?> req) {
448 * The backend has agreed that the transaction has entered PRE_COMMIT phase, meaning it will be committed
449 * to storage after the timeout completes.
451 * All state has been replicated to the backend, hence we do not need to keep it around. Retain only
452 * the precommit request, so we know which request to use for resync.
454 LOG.debug("Transaction {} preCommit completed, clearing successfulRequests", this);
455 successfulRequests.clear();
457 // TODO: this works, but can contain some useless state (like batched operations). Create an empty
458 // equivalent of this request and store that.
459 recordSuccessfulRequest(req);
462 final void doCommit(final VotingFuture<?> ret) {
466 sendRequest(new TransactionDoCommitRequest(getIdentifier(), nextSequence(), localActor()), t -> {
467 if (t instanceof TransactionCommitSuccess) {
469 } else if (t instanceof RequestFailure) {
470 ret.voteNo(((RequestFailure<?, ?>) t).getCause().unwrap());
472 ret.voteNo(new IllegalStateException("Unhandled response " + t.getClass()));
475 LOG.debug("Transaction {} doCommit completed", this);
480 final void sendPurge() {
481 successfulRequests.clear();
483 final TransactionRequest<?> req = new TransactionPurgeRequest(getIdentifier(), nextSequence(), localActor());
484 sendRequest(req, t -> {
485 LOG.debug("Transaction {} purge completed", this);
486 parent.completeTransaction(this);
490 final void enqueuePurge(final long enqueuedTicks) {
491 successfulRequests.clear();
493 final TransactionRequest<?> req = new TransactionPurgeRequest(getIdentifier(), nextSequence(), localActor());
494 enqueueRequest(req, t -> {
495 LOG.debug("Transaction {} purge completed", this);
496 parent.completeTransaction(this);
500 // Called with the connection unlocked
501 final synchronized void startReconnect() {
502 // At this point canCommit/directCommit are blocked, we assert a new successor state, retrieving the previous
503 // state. This method is called with the queue still unlocked.
504 final SuccessorState nextState = new SuccessorState();
505 final State prevState = STATE_UPDATER.getAndSet(this, nextState);
507 LOG.debug("Start reconnect of proxy {} previous state {}", this, prevState);
508 Verify.verify(!(prevState instanceof SuccessorState), "Proxy %s duplicate reconnect attempt after %s", this,
511 // We have asserted a slow-path state, seal(), canCommit(), directCommit() are forced to slow paths, which will
512 // wait until we unblock nextState's latch before accessing state. Now we record prevState for later use and we
514 nextState.setPrevState(prevState);
517 // Called with the connection locked
518 final void replayMessages(final AbstractProxyTransaction successor,
519 final Iterable<ConnectionEntry> enqueuedEntries) {
520 final SuccessorState local = getSuccessorState();
521 local.setSuccessor(successor);
523 // Replay successful requests first
524 if (!successfulRequests.isEmpty()) {
525 // We need to find a good timestamp to use for successful requests, as we do not want to time them out
526 // nor create timing inconsistencies in the queue -- requests are expected to be ordered by their enqueue
527 // time. We will pick the time of the first entry available. If there is none, we will just use current
528 // time, as all other requests will get enqueued afterwards.
529 final ConnectionEntry firstInQueue = Iterables.getFirst(enqueuedEntries, null);
530 final long now = firstInQueue != null ? firstInQueue.getEnqueuedTicks() : parent.currentTime();
532 for (Object obj : successfulRequests) {
533 if (obj instanceof TransactionRequest) {
534 LOG.debug("Forwarding successful request {} to successor {}", obj, successor);
535 successor.replayRequest((TransactionRequest<?>) obj, resp -> { }, now);
537 Verify.verify(obj instanceof IncrementSequence);
538 final IncrementSequence increment = (IncrementSequence) obj;
539 successor.replayRequest(new IncrementTransactionSequenceRequest(getIdentifier(),
540 increment.getSequence(), localActor(), isSnapshotOnly(), increment.getDelta()), resp -> { },
542 LOG.debug("Incrementing sequence {} to successor {}", obj, successor);
545 LOG.debug("{} replayed {} successful requests", getIdentifier(), successfulRequests.size());
546 successfulRequests.clear();
549 // Now replay whatever is in the connection
550 final Iterator<ConnectionEntry> it = enqueuedEntries.iterator();
551 while (it.hasNext()) {
552 final ConnectionEntry e = it.next();
553 final Request<?, ?> req = e.getRequest();
555 if (getIdentifier().equals(req.getTarget())) {
556 Verify.verify(req instanceof TransactionRequest, "Unhandled request %s", req);
557 LOG.debug("Replaying queued request {} to successor {}", req, successor);
558 successor.replayRequest((TransactionRequest<?>) req, e.getCallback(), e.getEnqueuedTicks());
564 * Check the state at which we have started the reconnect attempt. State transitions triggered while we were
565 * reconnecting have been forced to slow paths, which will be unlocked once we unblock the state latch
566 * at the end of this method.
568 final State prevState = local.getPrevState();
569 if (SEALED.equals(prevState)) {
570 LOG.debug("Proxy {} reconnected while being sealed, propagating state to successor {}", this, successor);
571 flushState(successor);
572 successor.ensureSealed();
577 * Invoked from {@link #replayMessages(AbstractProxyTransaction, Iterable)} to have successor adopt an in-flight
581 * Note: this method is invoked by the predecessor on the successor.
583 * @param request Request which needs to be forwarded
584 * @param callback Callback to be invoked once the request completes
585 * @param enqueuedTicks ticker-based time stamp when the request was enqueued
587 private void replayRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback,
588 final long enqueuedTicks) {
589 if (request instanceof AbstractLocalTransactionRequest) {
590 handleReplayedLocalRequest((AbstractLocalTransactionRequest<?>) request, callback, enqueuedTicks);
592 handleReplayedRemoteRequest(request, callback, enqueuedTicks);
596 // Called with the connection locked
597 final void finishReconnect() {
598 final SuccessorState local = getSuccessorState();
599 LOG.debug("Finishing reconnect of proxy {}", this);
601 // All done, release the latch, unblocking seal() and canCommit() slow paths
606 * Invoked from a retired connection for requests which have been in-flight and need to be re-adjusted
607 * and forwarded to the successor connection.
609 * @param request Request to be forwarded
610 * @param callback Original callback
612 final void forwardRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
613 forwardToSuccessor(getSuccessorState().getSuccessor(), request, callback);
616 final void forwardToSuccessor(final AbstractProxyTransaction successor, final TransactionRequest<?> request,
617 final Consumer<Response<?, ?>> callback) {
618 if (successor instanceof LocalProxyTransaction) {
619 forwardToLocal((LocalProxyTransaction)successor, request, callback);
620 } else if (successor instanceof RemoteProxyTransaction) {
621 forwardToRemote((RemoteProxyTransaction)successor, request, callback);
623 throw new IllegalStateException("Unhandled successor " + successor);
627 abstract boolean isSnapshotOnly();
629 abstract void doDelete(YangInstanceIdentifier path);
631 abstract void doMerge(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
633 abstract void doWrite(YangInstanceIdentifier path, NormalizedNode<?, ?> data);
635 abstract CheckedFuture<Boolean, ReadFailedException> doExists(YangInstanceIdentifier path);
637 abstract CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> doRead(YangInstanceIdentifier path);
639 abstract void doSeal();
641 abstract void doAbort();
644 abstract void flushState(AbstractProxyTransaction successor);
646 abstract TransactionRequest<?> commitRequest(boolean coordinated);
649 * Replay a request originating in this proxy to a successor remote proxy.
651 abstract void forwardToRemote(RemoteProxyTransaction successor, TransactionRequest<?> request,
652 Consumer<Response<?, ?>> callback);
655 * Replay a request originating in this proxy to a successor local proxy.
657 abstract void forwardToLocal(LocalProxyTransaction successor, TransactionRequest<?> request,
658 Consumer<Response<?, ?>> callback);
661 * Invoked from {@link LocalProxyTransaction} when it replays its successful requests to its successor.
664 * Note: this method is invoked by the predecessor on the successor.
666 * @param request Request which needs to be forwarded
667 * @param callback Callback to be invoked once the request completes
668 * @param enqueuedTicks Time stamp to use for enqueue time
670 abstract void handleReplayedLocalRequest(AbstractLocalTransactionRequest<?> request,
671 @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
674 * Invoked from {@link RemoteProxyTransaction} when it replays its successful requests to its successor.
677 * Note: this method is invoked by the predecessor on the successor.
679 * @param request Request which needs to be forwarded
680 * @param callback Callback to be invoked once the request completes
681 * @param enqueuedTicks Time stamp to use for enqueue time
683 abstract void handleReplayedRemoteRequest(TransactionRequest<?> request,
684 @Nullable Consumer<Response<?, ?>> callback, long enqueuedTicks);
687 public final String toString() {
688 return MoreObjects.toStringHelper(this).add("identifier", getIdentifier()).add("state", state).toString();