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 attept to reconnect
57 static final long 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
64 static final long REQUEST_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(2);
67 * No progress timeout. A client fails to make any forward progress in this time, it will terminate itself.
70 static final long NO_PROGRESS_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(15);
72 // Emit a debug entry if we sleep for more that this amount
73 private static final long DEBUG_DELAY_NANOS = TimeUnit.MILLISECONDS.toNanos(100);
75 private final Lock lock = new ReentrantLock();
76 private final ClientActorContext context;
78 private final TransmitQueue queue;
79 private final Long cookie;
82 private boolean haveTimer;
85 * Time reference when we saw any activity from the backend.
87 private long lastReceivedTicks;
89 private volatile RequestException poisoned;
91 // Do not allow subclassing outside of this package
92 AbstractClientConnection(final ClientActorContext context, final Long cookie,
93 final TransmitQueue queue) {
94 this.context = Preconditions.checkNotNull(context);
95 this.cookie = Preconditions.checkNotNull(cookie);
96 this.queue = Preconditions.checkNotNull(queue);
97 this.lastReceivedTicks = currentTime();
100 // Do not allow subclassing outside of this package
101 AbstractClientConnection(final AbstractClientConnection<T> oldConnection, final int targetQueueSize) {
102 this.context = oldConnection.context;
103 this.cookie = oldConnection.cookie;
104 this.queue = new TransmitQueue.Halted(targetQueueSize);
105 this.lastReceivedTicks = oldConnection.lastReceivedTicks;
108 public final ClientActorContext context() {
112 public final @Nonnull Long cookie() {
116 public final ActorRef localActor() {
117 return context.self();
120 public final long currentTime() {
121 return context.ticker().read();
125 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
128 * <p>This method may put the caller thread to sleep in order to throttle the request rate.
129 * The callback may be called before the sleep finishes.
131 * @param request Request to send
132 * @param callback Callback to invoke
134 public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
135 final long now = currentTime();
136 final long delay = enqueueEntry(new ConnectionEntry(request, callback, now), now);
138 if (delay >= DEBUG_DELAY_NANOS && LOG.isDebugEnabled()) {
139 LOG.debug("Sleeping for {}ms", TimeUnit.NANOSECONDS.toMillis(delay));
141 TimeUnit.NANOSECONDS.sleep(delay);
142 } catch (InterruptedException e) {
143 Thread.currentThread().interrupt();
144 LOG.debug("Interrupted after sleeping {}ns", e, currentTime() - now);
149 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
153 * Note that unlike {@link #sendRequest(Request, Consumer)}, this method does not exert backpressure, hence it
154 * should never be called from an application thread.
156 * @param request Request to send
157 * @param callback Callback to invoke
158 * @param enqueuedTicks Time (according to {@link #currentTime()} of request enqueue
160 public final void enqueueRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback,
161 final long enqueuedTicks) {
162 enqueueEntry(new ConnectionEntry(request, callback, enqueuedTicks), currentTime());
165 public abstract Optional<T> getBackendInfo();
167 final Collection<ConnectionEntry> startReplay() {
169 return queue.drain();
173 final void finishReplay(final ReconnectForwarder forwarder) {
174 setForwarder(forwarder);
179 final void setForwarder(final ReconnectForwarder forwarder) {
180 queue.setForwarder(forwarder, currentTime());
184 abstract ClientActorBehavior<T> lockedReconnect(ClientActorBehavior<T> current,
185 RequestException runtimeRequestException);
187 final long enqueueEntry(final ConnectionEntry entry, final long now) {
190 final RequestException maybePoison = poisoned;
191 if (maybePoison != null) {
192 throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
195 if (queue.isEmpty()) {
196 // The queue is becoming non-empty, schedule a timer.
197 scheduleTimer(entry.getEnqueuedTicks() + REQUEST_TIMEOUT_NANOS - now);
199 return queue.enqueue(entry, now);
205 final ClientActorBehavior<T> reconnect(final ClientActorBehavior<T> current, final RequestException cause) {
208 return lockedReconnect(current, cause);
215 * Schedule a timer to fire on the actor thread after a delay.
217 * @param delay Delay, in nanoseconds
220 private void scheduleTimer(final long delay) {
222 LOG.debug("{}: timer already scheduled", context.persistenceId());
225 if (queue.hasSuccessor()) {
226 LOG.debug("{}: connection has successor, not scheduling timer", context.persistenceId());
230 // If the delay is negative, we need to schedule an action immediately. While the caller could have checked
231 // for that condition and take appropriate action, but this is more convenient and less error-prone.
232 final long normalized = delay <= 0 ? 0 : Math.min(delay, BACKEND_ALIVE_TIMEOUT_NANOS);
234 final FiniteDuration dur = FiniteDuration.fromNanos(normalized);
235 LOG.debug("{}: scheduling timeout in {}", context.persistenceId(), dur);
236 context.executeInActor(this::runTimer, dur);
241 * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
242 * in {@link #NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
244 * @param current Current behavior
245 * @return Next behavior to use
248 final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
249 final Optional<Long> delay;
254 final long now = currentTime();
255 // The following line is only reliable when queue is not forwarding, but such state should not last long.
256 // FIXME: BUG-8422: this may not be accurate w.r.t. replayed entries
257 final long ticksSinceProgress = queue.ticksStalling(now);
258 if (ticksSinceProgress >= NO_PROGRESS_TIMEOUT_NANOS) {
259 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
260 TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
262 lockedPoison(new NoProgressException(ticksSinceProgress));
263 current.removeConnection(this);
267 // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
268 // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
269 // return convention.
270 delay = lockedCheckTimeout(now);
272 // We have timed out. There is no point in scheduling a timer
273 return lockedReconnect(current, new RuntimeRequestException("Backend connection timed out",
274 new TimeoutException()));
277 if (delay.isPresent()) {
278 // If there is new delay, schedule a timer
279 scheduleTimer(delay.get());
289 final Optional<Long> checkTimeout(final long now) {
292 return lockedCheckTimeout(now);
298 long backendSilentTicks(final long now) {
299 return now - lastReceivedTicks;
303 * We are using tri-state return here to indicate one of three conditions:
304 * - if there is no timeout to schedule, return Optional.empty()
305 * - if there is a timeout to schedule, return a non-empty optional
306 * - if this connections has timed out, return null
308 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
309 justification = "Returning null Optional is documented in the API contract.")
311 private Optional<Long> lockedCheckTimeout(final long now) {
312 if (queue.isEmpty()) {
313 return Optional.empty();
316 final long backendSilentTicks = backendSilentTicks(now);
317 if (backendSilentTicks >= BACKEND_ALIVE_TIMEOUT_NANOS) {
318 LOG.debug("Connection {} has not seen activity from backend for {} nanoseconds, timing out", this,
323 int tasksTimedOut = 0;
324 for (ConnectionEntry head = queue.peek(); head != null; head = queue.peek()) {
325 final long beenOpen = now - head.getEnqueuedTicks();
326 if (beenOpen < REQUEST_TIMEOUT_NANOS) {
327 return Optional.of(REQUEST_TIMEOUT_NANOS - beenOpen);
332 LOG.debug("Connection {} timed out entryt {}", this, head);
333 head.complete(head.getRequest().toRequestFailure(
334 new RequestTimeoutException("Timed out after " + beenOpen + "ns")));
337 LOG.debug("Connection {} timed out {} tasks", this, tasksTimedOut);
338 if (tasksTimedOut != 0) {
339 queue.tryTransmit(now);
342 return Optional.empty();
345 final void poison(final RequestException cause) {
355 private void lockedPoison(final RequestException cause) {
356 poisoned = enrichPoison(cause);
360 RequestException enrichPoison(final RequestException ex) {
365 final RequestException poisoned() {
369 final void receiveResponse(final ResponseEnvelope<?> envelope) {
370 final long now = currentTime();
371 lastReceivedTicks = now;
373 final Optional<TransmittedConnectionEntry> maybeEntry;
376 maybeEntry = queue.complete(envelope, now);
381 if (maybeEntry.isPresent()) {
382 final TransmittedConnectionEntry entry = maybeEntry.get();
383 LOG.debug("Completing {} with {}", entry, envelope);
384 entry.complete(envelope.getMessage());
389 public final String toString() {
390 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
393 ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
394 return toStringHelper.add("client", context.getIdentifier()).add("cookie", cookie).add("poisoned", poisoned);