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.access.client;
10 import akka.actor.ActorRef;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Verify;
14 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
15 import java.util.ArrayDeque;
16 import java.util.Optional;
17 import java.util.Queue;
18 import java.util.concurrent.TimeUnit;
19 import java.util.function.Consumer;
20 import javax.annotation.Nonnull;
21 import javax.annotation.concurrent.GuardedBy;
22 import javax.annotation.concurrent.NotThreadSafe;
23 import org.opendaylight.controller.cluster.access.concepts.Request;
24 import org.opendaylight.controller.cluster.access.concepts.RequestException;
25 import org.opendaylight.controller.cluster.access.concepts.Response;
26 import org.opendaylight.controller.cluster.access.concepts.ResponseEnvelope;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import scala.concurrent.duration.FiniteDuration;
32 * Base class for a connection to the backend. Responsible to queueing and dispatch of requests toward the backend.
33 * Can be in three conceptual states: Connecting, Connected and Reconnecting, which are represented by public final
34 * classes exposed from this package.
36 * @author Robert Varga
39 public abstract class AbstractClientConnection<T extends BackendInfo> {
40 private static final Logger LOG = LoggerFactory.getLogger(AbstractClientConnection.class);
42 // Keep these constants in nanoseconds, as that prevents unnecessary conversions in the fast path
44 static final long NO_PROGRESS_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(15);
46 static final long REQUEST_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(30);
48 private final Queue<ConnectionEntry> pending;
49 private final ClientActorContext context;
50 private final Long cookie;
52 private volatile ReconnectForwarder successor;
53 private volatile RequestException poisoned;
54 private long lastProgress;
56 private AbstractClientConnection(final ClientActorContext context, final Long cookie,
57 final Queue<ConnectionEntry> pending) {
58 this.context = Preconditions.checkNotNull(context);
59 this.cookie = Preconditions.checkNotNull(cookie);
60 this.pending = Preconditions.checkNotNull(pending);
61 this.lastProgress = readTime();
64 // Do not allow subclassing outside of this package
65 AbstractClientConnection(final ClientActorContext context, final Long cookie) {
66 this(context, cookie, new ArrayDeque<>(1));
69 // Do not allow subclassing outside of this package
70 AbstractClientConnection(final AbstractClientConnection<T> oldConnection) {
71 this(oldConnection.context, oldConnection.cookie, oldConnection.pending);
74 public final ClientActorContext context() {
78 public final @Nonnull Long cookie() {
82 public final ActorRef localActor() {
83 return context.self();
86 final long readTime() {
87 return context.ticker().read();
90 final Queue<ConnectionEntry> pending() {
95 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
98 * @param request Request to send
99 * @param callback Callback to invoke
101 public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
102 Preconditions.checkState(poisoned == null, "Connection %s has been poisoned", this);
104 final ReconnectForwarder beforeQueue = successor;
105 final ConnectionEntry entry = new ConnectionEntry(request, callback, readTime());
106 if (beforeQueue != null) {
107 LOG.trace("Forwarding entry {} from {} to {}", entry, this, beforeQueue);
108 beforeQueue.forwardEntry(entry);
114 final ReconnectForwarder afterQueue = successor;
115 if (afterQueue != null) {
116 synchronized (this) {
117 spliceToSuccessor(afterQueue);
122 public final synchronized void setForwarder(final ReconnectForwarder forwarder) {
123 Verify.verify(successor == null, "Successor {} already set on connection {}", successor, this);
124 successor = Preconditions.checkNotNull(forwarder);
125 LOG.debug("Connection {} superseded by {}, splicing queue", this, successor);
126 spliceToSuccessor(forwarder);
129 public abstract Optional<T> getBackendInfo();
132 void spliceToSuccessor(final ReconnectForwarder successor) {
133 ConnectionEntry entry = pending.poll();
134 while (entry != null) {
135 successor.forwardEntry(entry);
136 entry = pending.poll();
140 final ConnectionEntry dequeEntry() {
141 lastProgress = readTime();
142 return pending.poll();
145 void enqueueEntry(final ConnectionEntry entry) {
150 * Schedule a timer to fire on the actor thread after a delay.
152 * @param delay Delay, in nanoseconds
154 private void scheduleTimer(final FiniteDuration delay) {
155 LOG.debug("{}: scheduling timeout in {}", context.persistenceId(), delay);
156 context.executeInActor(this::runTimer, delay);
160 * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
161 * in {@link #NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
163 * @param current Current behavior
164 * @return Next behavior to use
167 final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
168 final long now = readTime();
171 final long ticksSinceProgress = now - lastProgress;
172 if (ticksSinceProgress >= NO_PROGRESS_TIMEOUT_NANOS) {
173 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
174 TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
176 poison(new NoProgressException(ticksSinceProgress));
177 current.removeConnection(this);
182 // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
183 // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
184 // return convention.
185 final Optional<FiniteDuration> delay = checkTimeout(now);
187 // We have timed out. There is no point in scheduling a timer
188 return reconnectConnection(current);
191 if (delay.isPresent()) {
192 // If there is new delay, schedule a timer
193 scheduleTimer(delay.get());
200 return pending.isEmpty();
204 * We are using tri-state return here to indicate one of three conditions:
205 * - if there is no timeout to schedule, return Optional.empty()
206 * - if there is a timeout to schedule, return a non-empty optional
207 * - if this connections has timed out, return null
209 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
210 justification = "Returning null Optional is documented in the API contract.")
211 final Optional<FiniteDuration> checkTimeout(final ConnectionEntry head, final long now) {
213 return Optional.empty();
216 final long delay = head.getEnqueuedTicks() - now + REQUEST_TIMEOUT_NANOS;
218 LOG.debug("Connection {} timed out", this);
222 return Optional.of(FiniteDuration.apply(delay, TimeUnit.NANOSECONDS));
226 * We are using tri-state return here to indicate one of three conditions:
227 * - if there is no timeout to schedule, return Optional.empty()
228 * - if there is a timeout to schedule, return a non-empty optional
229 * - if this connections has timed out, return null
231 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
232 justification = "Returning null Optional is documented in the API contract.")
233 Optional<FiniteDuration> checkTimeout(final long now) {
234 return checkTimeout(pending.peek(), now);
237 static void poisonQueue(final Queue<? extends ConnectionEntry> queue, final RequestException cause) {
238 for (ConnectionEntry e : queue) {
239 final Request<?, ?> request = e.getRequest();
240 LOG.trace("Poisoning request {}", request, cause);
241 e.complete(request.toRequestFailure(cause));
246 void poison(final RequestException cause) {
248 poisonQueue(pending, cause);
252 final RequestException poisoned() {
256 abstract ClientActorBehavior<T> reconnectConnection(ClientActorBehavior<T> current);
258 abstract void receiveResponse(final ResponseEnvelope<?> envelope);