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.MoreObjects;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.Preconditions;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.util.Collection;
17 import java.util.List;
18 import java.util.Optional;
19 import java.util.concurrent.TimeUnit;
20 import java.util.concurrent.TimeoutException;
21 import java.util.concurrent.locks.Lock;
22 import java.util.concurrent.locks.ReentrantLock;
23 import java.util.function.Consumer;
24 import javax.annotation.Nonnull;
25 import javax.annotation.concurrent.GuardedBy;
26 import javax.annotation.concurrent.NotThreadSafe;
27 import org.opendaylight.controller.cluster.access.concepts.Request;
28 import org.opendaylight.controller.cluster.access.concepts.RequestException;
29 import org.opendaylight.controller.cluster.access.concepts.Response;
30 import org.opendaylight.controller.cluster.access.concepts.ResponseEnvelope;
31 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import scala.concurrent.duration.FiniteDuration;
37 * Base class for a connection to the backend. Responsible to queueing and dispatch of requests toward the backend.
38 * Can be in three conceptual states: Connecting, Connected and Reconnecting, which are represented by public final
39 * classes exposed from this package.
41 * @author Robert Varga
44 public abstract class AbstractClientConnection<T extends BackendInfo> {
45 private static final Logger LOG = LoggerFactory.getLogger(AbstractClientConnection.class);
48 * Timers involved in communication with the backend. There are three tiers which are spaced out to allow for
49 * recovery at each tier. Keep these constants in nanoseconds, as that prevents unnecessary conversions in the fast
53 * Backend aliveness timer. This is reset whenever we receive a response from the backend and kept armed whenever
54 * we have an outstanding request. If when this time expires, we tear down this connection and attempt to reconnect
57 public static final long DEFAULT_BACKEND_ALIVE_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(30);
60 * Request timeout. If the request fails to complete within this time since it was originally enqueued, we time
63 public static final long DEFAULT_REQUEST_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(2);
66 * No progress timeout. A client fails to make any forward progress in this time, it will terminate itself.
68 public static final long DEFAULT_NO_PROGRESS_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(15);
70 // Emit a debug entry if we sleep for more that this amount
71 private static final long DEBUG_DELAY_NANOS = TimeUnit.MILLISECONDS.toNanos(100);
73 // Upper bound on the time a thread is forced to sleep to keep queue size under control
74 private static final long MAX_DELAY_SECONDS = 5;
75 private static final long MAX_DELAY_NANOS = TimeUnit.SECONDS.toNanos(MAX_DELAY_SECONDS);
77 private final Lock lock = new ReentrantLock();
78 private final ClientActorContext context;
80 private final TransmitQueue queue;
81 private final Long cookie;
84 private boolean haveTimer;
87 * Time reference when we saw any activity from the backend.
89 private long lastReceivedTicks;
91 private volatile RequestException poisoned;
93 // Private constructor to avoid code duplication.
94 private AbstractClientConnection(final AbstractClientConnection<T> oldConn, final TransmitQueue newQueue) {
95 this.context = Preconditions.checkNotNull(oldConn.context);
96 this.cookie = Preconditions.checkNotNull(oldConn.cookie);
97 this.queue = Preconditions.checkNotNull(newQueue);
98 // Will be updated in finishReplay if needed.
99 this.lastReceivedTicks = oldConn.lastReceivedTicks;
102 // This constructor is only to be called by ConnectingClientConnection constructor.
103 // Do not allow subclassing outside of this package
104 AbstractClientConnection(final ClientActorContext context, final Long cookie, final int queueDepth) {
105 this.context = Preconditions.checkNotNull(context);
106 this.cookie = Preconditions.checkNotNull(cookie);
107 this.queue = new TransmitQueue.Halted(queueDepth);
108 this.lastReceivedTicks = currentTime();
111 // This constructor is only to be called (indirectly) by ReconnectingClientConnection constructor.
112 // Do not allow subclassing outside of this package
113 AbstractClientConnection(final AbstractClientConnection<T> oldConn) {
114 this(oldConn, new TransmitQueue.Halted(oldConn.queue, oldConn.currentTime()));
117 // This constructor is only to be called (indirectly) by ConnectedClientConnection constructor.
118 // Do not allow subclassing outside of this package
119 AbstractClientConnection(final AbstractClientConnection<T> oldConn, final T newBackend, final int queueDepth) {
120 this(oldConn, new TransmitQueue.Transmitting(oldConn.queue, queueDepth, newBackend, oldConn.currentTime(),
121 Preconditions.checkNotNull(oldConn.context).messageSlicer()));
124 public final ClientActorContext context() {
128 public final @Nonnull Long cookie() {
132 public final ActorRef localActor() {
133 return context.self();
136 public final long currentTime() {
137 return context.ticker().read();
141 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
144 * <p>This method may put the caller thread to sleep in order to throttle the request rate.
145 * The callback may be called before the sleep finishes.
147 * @param request Request to send
148 * @param callback Callback to invoke
150 public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
151 final long now = currentTime();
152 sendEntry(new ConnectionEntry(request, callback, now), now);
156 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
160 * Note that unlike {@link #sendRequest(Request, Consumer)}, this method does not exert backpressure, hence it
161 * should never be called from an application thread.
163 * @param request Request to send
164 * @param callback Callback to invoke
165 * @param enqueuedTicks Time (according to {@link #currentTime()} of request enqueue
167 public final void enqueueRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback,
168 final long enqueuedTicks) {
169 enqueueEntry(new ConnectionEntry(request, callback, enqueuedTicks), currentTime());
172 private long enqueueOrForward(final ConnectionEntry entry, final long now) {
175 commonEnqueue(entry, now);
176 return queue.enqueueOrForward(entry, now);
183 * Enqueue an entry, possibly also transmitting it.
185 public final void enqueueEntry(final ConnectionEntry entry, final long now) {
188 commonEnqueue(entry, now);
189 queue.enqueueOrReplay(entry, now);
196 private void commonEnqueue(final ConnectionEntry entry, final long now) {
197 final RequestException maybePoison = poisoned;
198 if (maybePoison != null) {
199 throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
202 if (queue.isEmpty()) {
203 // The queue is becoming non-empty, schedule a timer.
204 scheduleTimer(entry.getEnqueuedTicks() + context.config().getRequestTimeout() - now);
208 // To be called from ClientActorBehavior on ConnectedClientConnection after entries are replayed.
209 final void cancelDebt() {
210 queue.cancelDebt(currentTime());
213 public abstract Optional<T> getBackendInfo();
215 final Collection<ConnectionEntry> startReplay() {
217 return queue.drain();
221 final void finishReplay(final ReconnectForwarder forwarder) {
222 setForwarder(forwarder);
225 * The process of replaying all messages may have taken a significant chunk of time, depending on type
226 * of messages, queue depth and available processing power. In extreme situations this may have already
227 * exceeded BACKEND_ALIVE_TIMEOUT_NANOS, in which case we are running the risk of not making reasonable forward
228 * progress before we start a reconnect cycle.
230 * Note that the timer is armed after we have sent the first message, hence we should be seeing a response
231 * from the backend before we see a timeout, simply due to how the mailbox operates.
233 * At any rate, reset the timestamp once we complete reconnection (which an atomic transition from the
234 * perspective of outside world), as that makes it a bit easier to reason about timing of events.
236 lastReceivedTicks = currentTime();
241 final void setForwarder(final ReconnectForwarder forwarder) {
242 queue.setForwarder(forwarder, currentTime());
246 abstract ClientActorBehavior<T> lockedReconnect(ClientActorBehavior<T> current,
247 RequestException runtimeRequestException);
249 final void sendEntry(final ConnectionEntry entry, final long now) {
250 long delay = enqueueOrForward(entry, now);
252 if (delay >= DEBUG_DELAY_NANOS) {
253 if (delay > MAX_DELAY_NANOS) {
254 LOG.info("Capping {} throttle delay from {} to {} seconds", this,
255 TimeUnit.NANOSECONDS.toSeconds(delay), MAX_DELAY_SECONDS, new Throwable());
256 delay = MAX_DELAY_NANOS;
258 if (LOG.isDebugEnabled()) {
259 LOG.debug("{}: Sleeping for {}ms on connection {}", context.persistenceId(),
260 TimeUnit.NANOSECONDS.toMillis(delay), this);
263 TimeUnit.NANOSECONDS.sleep(delay);
264 } catch (InterruptedException e) {
265 Thread.currentThread().interrupt();
266 LOG.debug("Interrupted after sleeping {}ns", e, currentTime() - now);
270 final ClientActorBehavior<T> reconnect(final ClientActorBehavior<T> current, final RequestException cause) {
273 return lockedReconnect(current, cause);
280 * Schedule a timer to fire on the actor thread after a delay.
282 * @param delay Delay, in nanoseconds
285 private void scheduleTimer(final long delay) {
287 LOG.debug("{}: timer already scheduled on {}", context.persistenceId(), this);
290 if (queue.hasSuccessor()) {
291 LOG.debug("{}: connection {} has a successor, not scheduling timer", context.persistenceId(), this);
295 // If the delay is negative, we need to schedule an action immediately. While the caller could have checked
296 // for that condition and take appropriate action, but this is more convenient and less error-prone.
297 final long normalized = delay <= 0 ? 0 : Math.min(delay, context.config().getBackendAlivenessTimerInterval());
299 final FiniteDuration dur = FiniteDuration.fromNanos(normalized);
300 LOG.debug("{}: connection {} scheduling timeout in {}", context.persistenceId(), this, dur);
301 context.executeInActor(this::runTimer, dur);
306 * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
307 * in {@link #DEFAULT_NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
309 * @param current Current behavior
310 * @return Next behavior to use
313 final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
316 final List<ConnectionEntry> poisonEntries;
317 final NoProgressException poisonCause;
320 final long now = currentTime();
322 LOG.debug("{}: running timer on {}", context.persistenceId(), this);
324 // The following line is only reliable when queue is not forwarding, but such state should not last long.
325 // FIXME: BUG-8422: this may not be accurate w.r.t. replayed entries
326 final long ticksSinceProgress = queue.ticksStalling(now);
327 if (ticksSinceProgress < context.config().getNoProgressTimeout()) {
328 // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
329 // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual
330 // tri-state return convention.
331 final Optional<Long> delay = lockedCheckTimeout(now);
333 // We have timed out. There is no point in scheduling a timer
334 LOG.debug("{}: connection {} timed out", context.persistenceId(), this);
335 return lockedReconnect(current, new RuntimeRequestException("Backend connection timed out",
336 new TimeoutException()));
339 if (delay.isPresent()) {
340 // If there is new delay, schedule a timer
341 scheduleTimer(delay.get());
343 LOG.debug("{}: not scheduling timeout on {}", context.persistenceId(), this);
349 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
350 TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
351 poisonCause = new NoProgressException(ticksSinceProgress);
352 poisonEntries = lockedPoison(poisonCause);
353 current.removeConnection(this);
358 poison(poisonEntries, poisonCause);
363 final Optional<Long> checkTimeout(final long now) {
366 return lockedCheckTimeout(now);
372 long backendSilentTicks(final long now) {
373 return now - lastReceivedTicks;
377 * We are using tri-state return here to indicate one of three conditions:
378 * - if there is no timeout to schedule, return Optional.empty()
379 * - if there is a timeout to schedule, return a non-empty optional
380 * - if this connections has timed out, return null
382 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
383 justification = "Returning null Optional is documented in the API contract.")
385 private Optional<Long> lockedCheckTimeout(final long now) {
386 if (queue.isEmpty()) {
387 LOG.debug("{}: connection {} is empty", context.persistenceId(), this);
388 return Optional.empty();
391 final long backendSilentTicks = backendSilentTicks(now);
392 if (backendSilentTicks >= context.config().getBackendAlivenessTimerInterval()) {
393 LOG.debug("{}: Connection {} has not seen activity from backend for {} nanoseconds, timing out",
394 context.persistenceId(), this, backendSilentTicks);
398 int tasksTimedOut = 0;
399 for (ConnectionEntry head = queue.peek(); head != null; head = queue.peek()) {
400 final long beenOpen = now - head.getEnqueuedTicks();
401 final long requestTimeout = context.config().getRequestTimeout();
402 if (beenOpen < requestTimeout) {
403 return Optional.of(requestTimeout - beenOpen);
408 LOG.debug("{}: Connection {} timed out entry {}", context.persistenceId(), this, head);
410 timeoutEntry(head, beenOpen);
413 LOG.debug("Connection {} timed out {} tasks", this, tasksTimedOut);
414 if (tasksTimedOut != 0) {
415 queue.tryTransmit(now);
418 return Optional.empty();
421 private void timeoutEntry(final ConnectionEntry entry, final long beenOpen) {
422 // Timeouts needs to be re-scheduled on actor thread because we are holding the lock on the current queue,
423 // which may be the tail of a successor chain. This is a problem if the callback attempts to send a request
424 // because that will attempt to lock the chain from the start, potentially causing a deadlock if there is
425 // a concurrent attempt to transmit.
426 context.executeInActor(current -> {
427 final double time = beenOpen * 1.0 / 1_000_000_000;
428 entry.complete(entry.getRequest().toRequestFailure(
429 new RequestTimeoutException("Timed out after " + time + " seconds")));
434 final void poison(final RequestException cause) {
435 final List<ConnectionEntry> entries;
439 entries = lockedPoison(cause);
444 poison(entries, cause);
447 // Do not hold any locks while calling this
448 private static void poison(final Collection<? extends ConnectionEntry> entries, final RequestException cause) {
449 for (ConnectionEntry e : entries) {
450 final Request<?, ?> request = e.getRequest();
451 LOG.trace("Poisoning request {}", request, cause);
452 e.complete(request.toRequestFailure(cause));
457 private List<ConnectionEntry> lockedPoison(final RequestException cause) {
458 poisoned = enrichPoison(cause);
459 return queue.poison();
462 RequestException enrichPoison(final RequestException ex) {
467 final RequestException poisoned() {
471 void receiveResponse(final ResponseEnvelope<?> envelope) {
472 final long now = currentTime();
473 lastReceivedTicks = now;
475 final Optional<TransmittedConnectionEntry> maybeEntry;
478 maybeEntry = queue.complete(envelope, now);
483 if (maybeEntry.isPresent()) {
484 final TransmittedConnectionEntry entry = maybeEntry.get();
485 LOG.debug("Completing {} with {}", entry, envelope);
486 entry.complete(envelope.getMessage());
491 public final String toString() {
492 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
495 ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
496 return toStringHelper.add("client", context.getIdentifier()).add("cookie", cookie).add("poisoned", poisoned);