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.Optional;
17 import java.util.concurrent.TimeUnit;
18 import java.util.concurrent.locks.Lock;
19 import java.util.concurrent.locks.ReentrantLock;
20 import java.util.function.Consumer;
21 import javax.annotation.Nonnull;
22 import javax.annotation.concurrent.GuardedBy;
23 import javax.annotation.concurrent.NotThreadSafe;
24 import org.opendaylight.controller.cluster.access.concepts.Request;
25 import org.opendaylight.controller.cluster.access.concepts.RequestException;
26 import org.opendaylight.controller.cluster.access.concepts.Response;
27 import org.opendaylight.controller.cluster.access.concepts.ResponseEnvelope;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import scala.concurrent.duration.FiniteDuration;
33 * Base class for a connection to the backend. Responsible to queueing and dispatch of requests toward the backend.
34 * Can be in three conceptual states: Connecting, Connected and Reconnecting, which are represented by public final
35 * classes exposed from this package.
37 * @author Robert Varga
40 public abstract class AbstractClientConnection<T extends BackendInfo> {
41 private static final Logger LOG = LoggerFactory.getLogger(AbstractClientConnection.class);
44 * Timers involved in communication with the backend. There are three tiers which are spaced out to allow for
45 * recovery at each tier. Keep these constants in nanoseconds, as that prevents unnecessary conversions in the fast
49 * Backend aliveness timer. This is reset whenever we receive a response from the backend and kept armed whenever
50 * we have an outstanding request. If when this time expires, we tear down this connection and attept to reconnect
54 static final long BACKEND_ALIVE_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(30);
57 * Request timeout. If the request fails to complete within this time since it was originally enqueued, we time
61 static final long REQUEST_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(2);
64 * No progress timeout. A client fails to make any forward progress in this time, it will terminate itself.
67 static final long NO_PROGRESS_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(15);
69 private final Lock lock = new ReentrantLock();
70 private final ClientActorContext context;
72 private final TransmitQueue queue;
73 private final Long cookie;
76 private boolean haveTimer;
79 * Time reference when we saw any activity from the backend.
81 private long lastReceivedTicks;
83 private volatile RequestException poisoned;
85 // Do not allow subclassing outside of this package
86 AbstractClientConnection(final ClientActorContext context, final Long cookie,
87 final TransmitQueue queue) {
88 this.context = Preconditions.checkNotNull(context);
89 this.cookie = Preconditions.checkNotNull(cookie);
90 this.queue = Preconditions.checkNotNull(queue);
91 this.lastReceivedTicks = currentTime();
94 // Do not allow subclassing outside of this package
95 AbstractClientConnection(final AbstractClientConnection<T> oldConnection, final int targetQueueSize) {
96 this.context = oldConnection.context;
97 this.cookie = oldConnection.cookie;
98 this.queue = new TransmitQueue.Halted(targetQueueSize);
99 this.lastReceivedTicks = oldConnection.lastReceivedTicks;
102 public final ClientActorContext context() {
106 public final @Nonnull Long cookie() {
110 public final ActorRef localActor() {
111 return context.self();
114 public final long currentTime() {
115 return context.ticker().read();
119 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
122 * <p>This method may put the caller thread to sleep in order to throttle the request rate.
123 * The callback may be called before the sleep finishes.
125 * @param request Request to send
126 * @param callback Callback to invoke
128 public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
129 final long now = currentTime();
130 final long delay = enqueueEntry(new ConnectionEntry(request, callback, now), now);
132 TimeUnit.NANOSECONDS.sleep(delay);
133 } catch (InterruptedException e) {
134 Thread.currentThread().interrupt();
135 LOG.debug("Interrupted after sleeping {}ns", e, currentTime() - now);
140 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
144 * Note that unlike {@link #sendRequest(Request, Consumer)}, this method does not exert backpressure, hence it
145 * should never be called from an application thread.
147 * @param request Request to send
148 * @param callback Callback to invoke
149 * @param enqueuedTicks Time (according to {@link #currentTime()} of request enqueue
151 public final void enqueueRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback,
152 final long enqueuedTicks) {
153 enqueueEntry(new ConnectionEntry(request, callback, enqueuedTicks), currentTime());
156 public abstract Optional<T> getBackendInfo();
158 final Iterable<ConnectionEntry> startReplay() {
160 return queue.asIterable();
164 final void finishReplay(final ReconnectForwarder forwarder) {
165 setForwarder(forwarder);
170 final void setForwarder(final ReconnectForwarder forwarder) {
171 queue.setForwarder(forwarder, currentTime());
175 abstract ClientActorBehavior<T> lockedReconnect(ClientActorBehavior<T> current);
177 final long enqueueEntry(final ConnectionEntry entry, final long now) {
180 final RequestException maybePoison = poisoned;
181 if (maybePoison != null) {
182 throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
185 if (queue.isEmpty()) {
186 // The queue is becoming non-empty, schedule a timer.
187 scheduleTimer(entry.getEnqueuedTicks() + REQUEST_TIMEOUT_NANOS - now);
189 return queue.enqueue(entry, now);
195 final ClientActorBehavior<T> reconnect(final ClientActorBehavior<T> current) {
198 return lockedReconnect(current);
205 * Schedule a timer to fire on the actor thread after a delay.
207 * @param delay Delay, in nanoseconds
210 private void scheduleTimer(final long delay) {
212 LOG.debug("{}: timer already scheduled", context.persistenceId());
215 if (queue.hasSuccessor()) {
216 LOG.debug("{}: connection has successor, not scheduling timer", context.persistenceId());
220 // If the delay is negative, we need to schedule an action immediately. While the caller could have checked
221 // for that condition and take appropriate action, but this is more convenient and less error-prone.
222 final long normalized = delay <= 0 ? 0 : Math.min(delay, BACKEND_ALIVE_TIMEOUT_NANOS);
224 final FiniteDuration dur = FiniteDuration.fromNanos(normalized);
225 LOG.debug("{}: scheduling timeout in {}", context.persistenceId(), dur);
226 context.executeInActor(this::runTimer, dur);
231 * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
232 * in {@link #NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
234 * @param current Current behavior
235 * @return Next behavior to use
238 final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
239 final Optional<Long> delay;
244 final long now = currentTime();
245 // The following line is only reliable when queue is not forwarding, but such state should not last long.
246 // FIXME: BUG-8422: this may not be accurate w.r.t. replayed entries
247 final long ticksSinceProgress = queue.ticksStalling(now);
248 if (ticksSinceProgress >= NO_PROGRESS_TIMEOUT_NANOS) {
249 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
250 TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
252 lockedPoison(new NoProgressException(ticksSinceProgress));
253 current.removeConnection(this);
257 // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
258 // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
259 // return convention.
260 delay = lockedCheckTimeout(now);
262 // We have timed out. There is no point in scheduling a timer
263 return lockedReconnect(current);
266 if (delay.isPresent()) {
267 // If there is new delay, schedule a timer
268 scheduleTimer(delay.get());
278 final Optional<Long> checkTimeout(final long now) {
281 return lockedCheckTimeout(now);
288 * We are using tri-state return here to indicate one of three conditions:
289 * - if there is no timeout to schedule, return Optional.empty()
290 * - if there is a timeout to schedule, return a non-empty optional
291 * - if this connections has timed out, return null
293 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
294 justification = "Returning null Optional is documented in the API contract.")
296 private Optional<Long> lockedCheckTimeout(final long now) {
297 if (queue.isEmpty()) {
298 return Optional.empty();
301 final long backendSilentTicks = now - lastReceivedTicks;
302 if (backendSilentTicks >= BACKEND_ALIVE_TIMEOUT_NANOS) {
303 LOG.debug("Connection {} has not seen activity from backend for {} nanoseconds, timing out", this,
308 int tasksTimedOut = 0;
309 for (ConnectionEntry head = queue.peek(); head != null; head = queue.peek()) {
310 final long beenOpen = now - head.getEnqueuedTicks();
311 if (beenOpen < REQUEST_TIMEOUT_NANOS) {
312 return Optional.of(REQUEST_TIMEOUT_NANOS - beenOpen);
317 LOG.debug("Connection {} timed out entryt {}", this, head);
318 head.complete(head.getRequest().toRequestFailure(
319 new RequestTimeoutException("Timed out after " + beenOpen + "ns")));
322 LOG.debug("Connection {} timed out {} tasks", this, tasksTimedOut);
323 if (tasksTimedOut != 0) {
324 queue.tryTransmit(now);
327 return Optional.empty();
330 final void poison(final RequestException cause) {
340 private void lockedPoison(final RequestException cause) {
346 final RequestException poisoned() {
350 final void receiveResponse(final ResponseEnvelope<?> envelope) {
351 final long now = currentTime();
352 lastReceivedTicks = now;
354 final Optional<TransmittedConnectionEntry> maybeEntry;
357 maybeEntry = queue.complete(envelope, now);
362 if (maybeEntry.isPresent()) {
363 final TransmittedConnectionEntry entry = maybeEntry.get();
364 LOG.debug("Completing {} with {}", entry, envelope);
365 entry.complete(envelope.getMessage());
370 public final String toString() {
371 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
374 ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
375 return toStringHelper.add("client", context.getIdentifier()).add("cookie", cookie).add("poisoned", poisoned);