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.Optional;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.TimeoutException;
20 import java.util.concurrent.locks.Lock;
21 import java.util.concurrent.locks.ReentrantLock;
22 import java.util.function.Consumer;
23 import javax.annotation.Nonnull;
24 import javax.annotation.concurrent.GuardedBy;
25 import javax.annotation.concurrent.NotThreadSafe;
26 import org.opendaylight.controller.cluster.access.concepts.Request;
27 import org.opendaylight.controller.cluster.access.concepts.RequestException;
28 import org.opendaylight.controller.cluster.access.concepts.Response;
29 import org.opendaylight.controller.cluster.access.concepts.ResponseEnvelope;
30 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import scala.concurrent.duration.FiniteDuration;
36 * Base class for a connection to the backend. Responsible to queueing and dispatch of requests toward the backend.
37 * Can be in three conceptual states: Connecting, Connected and Reconnecting, which are represented by public final
38 * classes exposed from this package.
40 * @author Robert Varga
43 public abstract class AbstractClientConnection<T extends BackendInfo> {
44 private static final Logger LOG = LoggerFactory.getLogger(AbstractClientConnection.class);
47 * Timers involved in communication with the backend. There are three tiers which are spaced out to allow for
48 * recovery at each tier. Keep these constants in nanoseconds, as that prevents unnecessary conversions in the fast
52 * Backend aliveness timer. This is reset whenever we receive a response from the backend and kept armed whenever
53 * we have an outstanding request. If when this time expires, we tear down this connection and attempt to reconnect
56 public static final long DEFAULT_BACKEND_ALIVE_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(30);
59 * Request timeout. If the request fails to complete within this time since it was originally enqueued, we time
62 public static final long DEFAULT_REQUEST_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(2);
65 * No progress timeout. A client fails to make any forward progress in this time, it will terminate itself.
67 public static final long DEFAULT_NO_PROGRESS_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(15);
69 // Emit a debug entry if we sleep for more that this amount
70 private static final long DEBUG_DELAY_NANOS = TimeUnit.MILLISECONDS.toNanos(100);
72 // Upper bound on the time a thread is forced to sleep to keep queue size under control
73 private static final long MAX_DELAY_SECONDS = 5;
74 private static final long MAX_DELAY_NANOS = TimeUnit.SECONDS.toNanos(MAX_DELAY_SECONDS);
76 private final Lock lock = new ReentrantLock();
77 private final ClientActorContext context;
79 private final TransmitQueue queue;
80 private final Long cookie;
83 private boolean haveTimer;
86 * Time reference when we saw any activity from the backend.
88 private long lastReceivedTicks;
90 private volatile RequestException poisoned;
92 // Private constructor to avoid code duplication.
93 private AbstractClientConnection(final AbstractClientConnection<T> oldConn, final TransmitQueue newQueue) {
94 this.context = Preconditions.checkNotNull(oldConn.context);
95 this.cookie = Preconditions.checkNotNull(oldConn.cookie);
96 this.queue = Preconditions.checkNotNull(newQueue);
97 // Will be updated in finishReplay if needed.
98 this.lastReceivedTicks = oldConn.lastReceivedTicks;
101 // This constructor is only to be called by ConnectingClientConnection constructor.
102 // Do not allow subclassing outside of this package
103 AbstractClientConnection(final ClientActorContext context, final Long cookie, final int queueDepth) {
104 this.context = Preconditions.checkNotNull(context);
105 this.cookie = Preconditions.checkNotNull(cookie);
106 this.queue = new TransmitQueue.Halted(queueDepth);
107 this.lastReceivedTicks = currentTime();
110 // This constructor is only to be called (indirectly) by ReconnectingClientConnection constructor.
111 // Do not allow subclassing outside of this package
112 AbstractClientConnection(final AbstractClientConnection<T> oldConn) {
113 this(oldConn, new TransmitQueue.Halted(oldConn.queue, oldConn.currentTime()));
116 // This constructor is only to be called (indirectly) by ConnectedClientConnection constructor.
117 // Do not allow subclassing outside of this package
118 AbstractClientConnection(final AbstractClientConnection<T> oldConn, final T newBackend, final int queueDepth) {
119 this(oldConn, new TransmitQueue.Transmitting(oldConn.queue, queueDepth, newBackend, oldConn.currentTime(),
120 Preconditions.checkNotNull(oldConn.context).messageSlicer()));
123 public final ClientActorContext context() {
127 public final @Nonnull Long cookie() {
131 public final ActorRef localActor() {
132 return context.self();
135 public final long currentTime() {
136 return context.ticker().read();
140 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
143 * <p>This method may put the caller thread to sleep in order to throttle the request rate.
144 * The callback may be called before the sleep finishes.
146 * @param request Request to send
147 * @param callback Callback to invoke
149 public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
150 final long now = currentTime();
151 sendEntry(new ConnectionEntry(request, callback, now), now);
155 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
159 * Note that unlike {@link #sendRequest(Request, Consumer)}, this method does not exert backpressure, hence it
160 * should never be called from an application thread.
162 * @param request Request to send
163 * @param callback Callback to invoke
164 * @param enqueuedTicks Time (according to {@link #currentTime()} of request enqueue
166 public final void enqueueRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback,
167 final long enqueuedTicks) {
168 enqueueEntry(new ConnectionEntry(request, callback, enqueuedTicks), currentTime());
171 private long enqueueOrForward(final ConnectionEntry entry, final long now) {
174 commonEnqueue(entry, now);
175 return queue.enqueueOrForward(entry, now);
182 * Enqueue an entry, possibly also transmitting it.
184 public final void enqueueEntry(final ConnectionEntry entry, final long now) {
187 commonEnqueue(entry, now);
188 queue.enqueueOrReplay(entry, now);
195 private void commonEnqueue(final ConnectionEntry entry, final long now) {
196 final RequestException maybePoison = poisoned;
197 if (maybePoison != null) {
198 throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
201 if (queue.isEmpty()) {
202 // The queue is becoming non-empty, schedule a timer.
203 scheduleTimer(entry.getEnqueuedTicks() + context.config().getRequestTimeout() - now);
207 // To be called from ClientActorBehavior on ConnectedClientConnection after entries are replayed.
208 final void cancelDebt() {
209 queue.cancelDebt(currentTime());
212 public abstract Optional<T> getBackendInfo();
214 final Collection<ConnectionEntry> startReplay() {
216 return queue.drain();
220 final void finishReplay(final ReconnectForwarder forwarder) {
221 setForwarder(forwarder);
224 * The process of replaying all messages may have taken a significant chunk of time, depending on type
225 * of messages, queue depth and available processing power. In extreme situations this may have already
226 * exceeded BACKEND_ALIVE_TIMEOUT_NANOS, in which case we are running the risk of not making reasonable forward
227 * progress before we start a reconnect cycle.
229 * Note that the timer is armed after we have sent the first message, hence we should be seeing a response
230 * from the backend before we see a timeout, simply due to how the mailbox operates.
232 * At any rate, reset the timestamp once we complete reconnection (which an atomic transition from the
233 * perspective of outside world), as that makes it a bit easier to reason about timing of events.
235 lastReceivedTicks = currentTime();
240 final void setForwarder(final ReconnectForwarder forwarder) {
241 queue.setForwarder(forwarder, currentTime());
245 abstract ClientActorBehavior<T> lockedReconnect(ClientActorBehavior<T> current,
246 RequestException runtimeRequestException);
248 final void sendEntry(final ConnectionEntry entry, final long now) {
249 long delay = enqueueOrForward(entry, now);
251 if (delay >= DEBUG_DELAY_NANOS) {
252 if (delay > MAX_DELAY_NANOS) {
253 LOG.info("Capping {} throttle delay from {} to {} seconds", this,
254 TimeUnit.NANOSECONDS.toSeconds(delay), MAX_DELAY_SECONDS, new Throwable());
255 delay = MAX_DELAY_NANOS;
257 if (LOG.isDebugEnabled()) {
258 LOG.debug("{}: Sleeping for {}ms on connection {}", context.persistenceId(),
259 TimeUnit.NANOSECONDS.toMillis(delay), this);
262 TimeUnit.NANOSECONDS.sleep(delay);
263 } catch (InterruptedException e) {
264 Thread.currentThread().interrupt();
265 LOG.debug("Interrupted after sleeping {}ns", e, currentTime() - now);
269 final ClientActorBehavior<T> reconnect(final ClientActorBehavior<T> current, final RequestException cause) {
272 return lockedReconnect(current, cause);
279 * Schedule a timer to fire on the actor thread after a delay.
281 * @param delay Delay, in nanoseconds
284 private void scheduleTimer(final long delay) {
286 LOG.debug("{}: timer already scheduled on {}", context.persistenceId(), this);
289 if (queue.hasSuccessor()) {
290 LOG.debug("{}: connection {} has a successor, not scheduling timer", context.persistenceId(), this);
294 // If the delay is negative, we need to schedule an action immediately. While the caller could have checked
295 // for that condition and take appropriate action, but this is more convenient and less error-prone.
296 final long normalized = delay <= 0 ? 0 : Math.min(delay, context.config().getBackendAlivenessTimerInterval());
298 final FiniteDuration dur = FiniteDuration.fromNanos(normalized);
299 LOG.debug("{}: connection {} scheduling timeout in {}", context.persistenceId(), this, dur);
300 context.executeInActor(this::runTimer, dur);
305 * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
306 * in {@link #DEFAULT_NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
308 * @param current Current behavior
309 * @return Next behavior to use
312 final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
313 final Optional<Long> delay;
318 final long now = currentTime();
320 LOG.debug("{}: running timer on {}", context.persistenceId(), this);
322 // The following line is only reliable when queue is not forwarding, but such state should not last long.
323 // FIXME: BUG-8422: this may not be accurate w.r.t. replayed entries
324 final long ticksSinceProgress = queue.ticksStalling(now);
325 if (ticksSinceProgress >= context.config().getNoProgressTimeout()) {
326 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
327 TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
329 lockedPoison(new NoProgressException(ticksSinceProgress));
330 current.removeConnection(this);
334 // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
335 // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
336 // return convention.
337 delay = lockedCheckTimeout(now);
339 // We have timed out. There is no point in scheduling a timer
340 LOG.debug("{}: connection {} timed out", context.persistenceId(), this);
341 return lockedReconnect(current, new RuntimeRequestException("Backend connection timed out",
342 new TimeoutException()));
345 if (delay.isPresent()) {
346 // If there is new delay, schedule a timer
347 scheduleTimer(delay.get());
349 LOG.debug("{}: not scheduling timeout on {}", context.persistenceId(), this);
359 final Optional<Long> checkTimeout(final long now) {
362 return lockedCheckTimeout(now);
368 long backendSilentTicks(final long now) {
369 return now - lastReceivedTicks;
373 * We are using tri-state return here to indicate one of three conditions:
374 * - if there is no timeout to schedule, return Optional.empty()
375 * - if there is a timeout to schedule, return a non-empty optional
376 * - if this connections has timed out, return null
378 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
379 justification = "Returning null Optional is documented in the API contract.")
381 private Optional<Long> lockedCheckTimeout(final long now) {
382 if (queue.isEmpty()) {
383 LOG.debug("{}: connection {} is empty", context.persistenceId(), this);
384 return Optional.empty();
387 final long backendSilentTicks = backendSilentTicks(now);
388 if (backendSilentTicks >= context.config().getBackendAlivenessTimerInterval()) {
389 LOG.debug("{}: Connection {} has not seen activity from backend for {} nanoseconds, timing out",
390 context.persistenceId(), this, backendSilentTicks);
394 int tasksTimedOut = 0;
395 for (ConnectionEntry head = queue.peek(); head != null; head = queue.peek()) {
396 final long beenOpen = now - head.getEnqueuedTicks();
397 final long requestTimeout = context.config().getRequestTimeout();
398 if (beenOpen < requestTimeout) {
399 return Optional.of(requestTimeout - beenOpen);
404 LOG.debug("{}: Connection {} timed out entry {}", context.persistenceId(), this, head);
406 timeoutEntry(head, beenOpen);
409 LOG.debug("Connection {} timed out {} tasks", this, tasksTimedOut);
410 if (tasksTimedOut != 0) {
411 queue.tryTransmit(now);
414 return Optional.empty();
417 private void timeoutEntry(final ConnectionEntry entry, final long beenOpen) {
418 // Timeouts needs to be re-scheduled on actor thread because we are holding the lock on the current queue,
419 // which may be the tail of a successor chain. This is a problem if the callback attempts to send a request
420 // because that will attempt to lock the chain from the start, potentially causing a deadlock if there is
421 // a concurrent attempt to transmit.
422 context.executeInActor(current -> {
423 final double time = beenOpen * 1.0 / 1_000_000_000;
424 entry.complete(entry.getRequest().toRequestFailure(
425 new RequestTimeoutException("Timed out after " + time + " seconds")));
430 final void poison(final RequestException cause) {
440 private void lockedPoison(final RequestException cause) {
441 poisoned = enrichPoison(cause);
445 RequestException enrichPoison(final RequestException ex) {
450 final RequestException poisoned() {
454 void receiveResponse(final ResponseEnvelope<?> envelope) {
455 final long now = currentTime();
456 lastReceivedTicks = now;
458 final Optional<TransmittedConnectionEntry> maybeEntry;
461 maybeEntry = queue.complete(envelope, now);
466 if (maybeEntry.isPresent()) {
467 final TransmittedConnectionEntry entry = maybeEntry.get();
468 LOG.debug("Completing {} with {}", entry, envelope);
469 entry.complete(envelope.getMessage());
474 public final String toString() {
475 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
478 ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
479 return toStringHelper.add("client", context.getIdentifier()).add("cookie", cookie).add("poisoned", poisoned);