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 private final Lock lock = new ReentrantLock();
73 private final ClientActorContext context;
75 private final TransmitQueue queue;
76 private final Long cookie;
79 private boolean haveTimer;
82 * Time reference when we saw any activity from the backend.
84 private long lastReceivedTicks;
86 private volatile RequestException poisoned;
88 // Do not allow subclassing outside of this package
89 AbstractClientConnection(final ClientActorContext context, final Long cookie,
90 final TransmitQueue queue) {
91 this.context = Preconditions.checkNotNull(context);
92 this.cookie = Preconditions.checkNotNull(cookie);
93 this.queue = Preconditions.checkNotNull(queue);
94 this.lastReceivedTicks = currentTime();
97 // Do not allow subclassing outside of this package
98 AbstractClientConnection(final AbstractClientConnection<T> oldConnection, final int targetQueueSize) {
99 this.context = oldConnection.context;
100 this.cookie = oldConnection.cookie;
101 this.queue = new TransmitQueue.Halted(targetQueueSize);
102 this.lastReceivedTicks = oldConnection.lastReceivedTicks;
105 public final ClientActorContext context() {
109 public final @Nonnull Long cookie() {
113 public final ActorRef localActor() {
114 return context.self();
117 public final long currentTime() {
118 return context.ticker().read();
122 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
125 * <p>This method may put the caller thread to sleep in order to throttle the request rate.
126 * The callback may be called before the sleep finishes.
128 * @param request Request to send
129 * @param callback Callback to invoke
131 public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
132 final long now = currentTime();
133 final long delay = enqueueEntry(new ConnectionEntry(request, callback, now), now);
135 TimeUnit.NANOSECONDS.sleep(delay);
136 } catch (InterruptedException e) {
137 Thread.currentThread().interrupt();
138 LOG.debug("Interrupted after sleeping {}ns", e, currentTime() - now);
143 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
147 * Note that unlike {@link #sendRequest(Request, Consumer)}, this method does not exert backpressure, hence it
148 * should never be called from an application thread.
150 * @param request Request to send
151 * @param callback Callback to invoke
152 * @param enqueuedTicks Time (according to {@link #currentTime()} of request enqueue
154 public final void enqueueRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback,
155 final long enqueuedTicks) {
156 enqueueEntry(new ConnectionEntry(request, callback, enqueuedTicks), currentTime());
159 public abstract Optional<T> getBackendInfo();
161 final Collection<ConnectionEntry> startReplay() {
163 return queue.drain();
167 final void finishReplay(final ReconnectForwarder forwarder) {
168 setForwarder(forwarder);
173 final void setForwarder(final ReconnectForwarder forwarder) {
174 queue.setForwarder(forwarder, currentTime());
178 abstract ClientActorBehavior<T> lockedReconnect(ClientActorBehavior<T> current,
179 RequestException runtimeRequestException);
181 final long enqueueEntry(final ConnectionEntry entry, final long now) {
184 final RequestException maybePoison = poisoned;
185 if (maybePoison != null) {
186 throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
189 if (queue.isEmpty()) {
190 // The queue is becoming non-empty, schedule a timer.
191 scheduleTimer(entry.getEnqueuedTicks() + REQUEST_TIMEOUT_NANOS - now);
193 return queue.enqueue(entry, now);
199 final ClientActorBehavior<T> reconnect(final ClientActorBehavior<T> current, final RequestException cause) {
202 return lockedReconnect(current, cause);
209 * Schedule a timer to fire on the actor thread after a delay.
211 * @param delay Delay, in nanoseconds
214 private void scheduleTimer(final long delay) {
216 LOG.debug("{}: timer already scheduled", context.persistenceId());
219 if (queue.hasSuccessor()) {
220 LOG.debug("{}: connection has successor, not scheduling timer", context.persistenceId());
224 // If the delay is negative, we need to schedule an action immediately. While the caller could have checked
225 // for that condition and take appropriate action, but this is more convenient and less error-prone.
226 final long normalized = delay <= 0 ? 0 : Math.min(delay, BACKEND_ALIVE_TIMEOUT_NANOS);
228 final FiniteDuration dur = FiniteDuration.fromNanos(normalized);
229 LOG.debug("{}: scheduling timeout in {}", context.persistenceId(), dur);
230 context.executeInActor(this::runTimer, dur);
235 * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
236 * in {@link #NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
238 * @param current Current behavior
239 * @return Next behavior to use
242 final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
243 final Optional<Long> delay;
248 final long now = currentTime();
249 // The following line is only reliable when queue is not forwarding, but such state should not last long.
250 // FIXME: BUG-8422: this may not be accurate w.r.t. replayed entries
251 final long ticksSinceProgress = queue.ticksStalling(now);
252 if (ticksSinceProgress >= NO_PROGRESS_TIMEOUT_NANOS) {
253 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
254 TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
256 lockedPoison(new NoProgressException(ticksSinceProgress));
257 current.removeConnection(this);
261 // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
262 // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
263 // return convention.
264 delay = lockedCheckTimeout(now);
266 // We have timed out. There is no point in scheduling a timer
267 return lockedReconnect(current, new RuntimeRequestException("Backend connection timed out",
268 new TimeoutException()));
271 if (delay.isPresent()) {
272 // If there is new delay, schedule a timer
273 scheduleTimer(delay.get());
283 final Optional<Long> checkTimeout(final long now) {
286 return lockedCheckTimeout(now);
293 * We are using tri-state return here to indicate one of three conditions:
294 * - if there is no timeout to schedule, return Optional.empty()
295 * - if there is a timeout to schedule, return a non-empty optional
296 * - if this connections has timed out, return null
298 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
299 justification = "Returning null Optional is documented in the API contract.")
301 private Optional<Long> lockedCheckTimeout(final long now) {
302 if (queue.isEmpty()) {
303 return Optional.empty();
306 final long backendSilentTicks = now - lastReceivedTicks;
307 if (backendSilentTicks >= BACKEND_ALIVE_TIMEOUT_NANOS) {
308 LOG.debug("Connection {} has not seen activity from backend for {} nanoseconds, timing out", this,
313 int tasksTimedOut = 0;
314 for (ConnectionEntry head = queue.peek(); head != null; head = queue.peek()) {
315 final long beenOpen = now - head.getEnqueuedTicks();
316 if (beenOpen < REQUEST_TIMEOUT_NANOS) {
317 return Optional.of(REQUEST_TIMEOUT_NANOS - beenOpen);
322 LOG.debug("Connection {} timed out entryt {}", this, head);
323 head.complete(head.getRequest().toRequestFailure(
324 new RequestTimeoutException("Timed out after " + beenOpen + "ns")));
327 LOG.debug("Connection {} timed out {} tasks", this, tasksTimedOut);
328 if (tasksTimedOut != 0) {
329 queue.tryTransmit(now);
332 return Optional.empty();
335 final void poison(final RequestException cause) {
345 private void lockedPoison(final RequestException cause) {
346 poisoned = enrichPoison(cause);
350 RequestException enrichPoison(final RequestException ex) {
355 final RequestException poisoned() {
359 final void receiveResponse(final ResponseEnvelope<?> envelope) {
360 final long now = currentTime();
361 lastReceivedTicks = now;
363 final Optional<TransmittedConnectionEntry> maybeEntry;
366 maybeEntry = queue.complete(envelope, now);
371 if (maybeEntry.isPresent()) {
372 final TransmittedConnectionEntry entry = maybeEntry.get();
373 LOG.debug("Completing {} with {}", entry, envelope);
374 entry.complete(envelope.getMessage());
379 public final String toString() {
380 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
383 ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
384 return toStringHelper.add("client", context.getIdentifier()).add("cookie", cookie).add("poisoned", poisoned);