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.locks.Lock;
20 import java.util.concurrent.locks.ReentrantLock;
21 import java.util.function.Consumer;
22 import javax.annotation.Nonnull;
23 import javax.annotation.concurrent.GuardedBy;
24 import javax.annotation.concurrent.NotThreadSafe;
25 import org.opendaylight.controller.cluster.access.concepts.Request;
26 import org.opendaylight.controller.cluster.access.concepts.RequestException;
27 import org.opendaylight.controller.cluster.access.concepts.Response;
28 import org.opendaylight.controller.cluster.access.concepts.ResponseEnvelope;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import scala.concurrent.duration.FiniteDuration;
34 * Base class for a connection to the backend. Responsible to queueing and dispatch of requests toward the backend.
35 * Can be in three conceptual states: Connecting, Connected and Reconnecting, which are represented by public final
36 * classes exposed from this package.
38 * @author Robert Varga
41 public abstract class AbstractClientConnection<T extends BackendInfo> {
42 private static final Logger LOG = LoggerFactory.getLogger(AbstractClientConnection.class);
45 * Timers involved in communication with the backend. There are three tiers which are spaced out to allow for
46 * recovery at each tier. Keep these constants in nanoseconds, as that prevents unnecessary conversions in the fast
50 * Backend aliveness timer. This is reset whenever we receive a response from the backend and kept armed whenever
51 * we have an outstanding request. If when this time expires, we tear down this connection and attept to reconnect
55 static final long BACKEND_ALIVE_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(30);
58 * Request timeout. If the request fails to complete within this time since it was originally enqueued, we time
62 static final long 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.
68 static final long NO_PROGRESS_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(15);
70 private final Lock lock = new ReentrantLock();
71 private final ClientActorContext context;
73 private final TransmitQueue queue;
74 private final Long cookie;
77 private boolean haveTimer;
80 * Time reference when we saw any activity from the backend.
82 private long lastReceivedTicks;
84 private volatile RequestException poisoned;
86 // Do not allow subclassing outside of this package
87 AbstractClientConnection(final ClientActorContext context, final Long cookie,
88 final TransmitQueue queue) {
89 this.context = Preconditions.checkNotNull(context);
90 this.cookie = Preconditions.checkNotNull(cookie);
91 this.queue = Preconditions.checkNotNull(queue);
92 this.lastReceivedTicks = currentTime();
95 // Do not allow subclassing outside of this package
96 AbstractClientConnection(final AbstractClientConnection<T> oldConnection, final int targetQueueSize) {
97 this.context = oldConnection.context;
98 this.cookie = oldConnection.cookie;
99 this.queue = new TransmitQueue.Halted(targetQueueSize);
100 this.lastReceivedTicks = oldConnection.lastReceivedTicks;
103 public final ClientActorContext context() {
107 public final @Nonnull Long cookie() {
111 public final ActorRef localActor() {
112 return context.self();
115 public final long currentTime() {
116 return context.ticker().read();
120 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
123 * <p>This method may put the caller thread to sleep in order to throttle the request rate.
124 * The callback may be called before the sleep finishes.
126 * @param request Request to send
127 * @param callback Callback to invoke
129 public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
130 final long now = currentTime();
131 final long delay = enqueueEntry(new ConnectionEntry(request, callback, now), now);
133 TimeUnit.NANOSECONDS.sleep(delay);
134 } catch (InterruptedException e) {
135 Thread.currentThread().interrupt();
136 LOG.debug("Interrupted after sleeping {}ns", e, currentTime() - now);
141 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
145 * Note that unlike {@link #sendRequest(Request, Consumer)}, this method does not exert backpressure, hence it
146 * should never be called from an application thread.
148 * @param request Request to send
149 * @param callback Callback to invoke
150 * @param enqueuedTicks Time (according to {@link #currentTime()} of request enqueue
152 public final void enqueueRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback,
153 final long enqueuedTicks) {
154 enqueueEntry(new ConnectionEntry(request, callback, enqueuedTicks), currentTime());
157 public abstract Optional<T> getBackendInfo();
159 final Collection<ConnectionEntry> startReplay() {
161 return queue.drain();
165 final void finishReplay(final ReconnectForwarder forwarder) {
166 setForwarder(forwarder);
171 final void setForwarder(final ReconnectForwarder forwarder) {
172 queue.setForwarder(forwarder, currentTime());
176 abstract ClientActorBehavior<T> lockedReconnect(ClientActorBehavior<T> current);
178 final long enqueueEntry(final ConnectionEntry entry, final long now) {
181 final RequestException maybePoison = poisoned;
182 if (maybePoison != null) {
183 throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
186 if (queue.isEmpty()) {
187 // The queue is becoming non-empty, schedule a timer.
188 scheduleTimer(entry.getEnqueuedTicks() + REQUEST_TIMEOUT_NANOS - now);
190 return queue.enqueue(entry, now);
196 final ClientActorBehavior<T> reconnect(final ClientActorBehavior<T> current) {
199 return lockedReconnect(current);
206 * Schedule a timer to fire on the actor thread after a delay.
208 * @param delay Delay, in nanoseconds
211 private void scheduleTimer(final long delay) {
213 LOG.debug("{}: timer already scheduled", context.persistenceId());
216 if (queue.hasSuccessor()) {
217 LOG.debug("{}: connection has successor, not scheduling timer", context.persistenceId());
221 // If the delay is negative, we need to schedule an action immediately. While the caller could have checked
222 // for that condition and take appropriate action, but this is more convenient and less error-prone.
223 final long normalized = delay <= 0 ? 0 : Math.min(delay, BACKEND_ALIVE_TIMEOUT_NANOS);
225 final FiniteDuration dur = FiniteDuration.fromNanos(normalized);
226 LOG.debug("{}: scheduling timeout in {}", context.persistenceId(), dur);
227 context.executeInActor(this::runTimer, dur);
232 * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
233 * in {@link #NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
235 * @param current Current behavior
236 * @return Next behavior to use
239 final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
240 final Optional<Long> delay;
245 final long now = currentTime();
246 // The following line is only reliable when queue is not forwarding, but such state should not last long.
247 // FIXME: BUG-8422: this may not be accurate w.r.t. replayed entries
248 final long ticksSinceProgress = queue.ticksStalling(now);
249 if (ticksSinceProgress >= NO_PROGRESS_TIMEOUT_NANOS) {
250 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
251 TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
253 lockedPoison(new NoProgressException(ticksSinceProgress));
254 current.removeConnection(this);
258 // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
259 // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
260 // return convention.
261 delay = lockedCheckTimeout(now);
263 // We have timed out. There is no point in scheduling a timer
264 return lockedReconnect(current);
267 if (delay.isPresent()) {
268 // If there is new delay, schedule a timer
269 scheduleTimer(delay.get());
279 final Optional<Long> checkTimeout(final long now) {
282 return lockedCheckTimeout(now);
289 * We are using tri-state return here to indicate one of three conditions:
290 * - if there is no timeout to schedule, return Optional.empty()
291 * - if there is a timeout to schedule, return a non-empty optional
292 * - if this connections has timed out, return null
294 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
295 justification = "Returning null Optional is documented in the API contract.")
297 private Optional<Long> lockedCheckTimeout(final long now) {
298 if (queue.isEmpty()) {
299 return Optional.empty();
302 final long backendSilentTicks = now - lastReceivedTicks;
303 if (backendSilentTicks >= BACKEND_ALIVE_TIMEOUT_NANOS) {
304 LOG.debug("Connection {} has not seen activity from backend for {} nanoseconds, timing out", this,
309 int tasksTimedOut = 0;
310 for (ConnectionEntry head = queue.peek(); head != null; head = queue.peek()) {
311 final long beenOpen = now - head.getEnqueuedTicks();
312 if (beenOpen < REQUEST_TIMEOUT_NANOS) {
313 return Optional.of(REQUEST_TIMEOUT_NANOS - beenOpen);
318 LOG.debug("Connection {} timed out entryt {}", this, head);
319 head.complete(head.getRequest().toRequestFailure(
320 new RequestTimeoutException("Timed out after " + beenOpen + "ns")));
323 LOG.debug("Connection {} timed out {} tasks", this, tasksTimedOut);
324 if (tasksTimedOut != 0) {
325 queue.tryTransmit(now);
328 return Optional.empty();
331 final void poison(final RequestException cause) {
341 private void lockedPoison(final RequestException cause) {
347 final RequestException poisoned() {
351 final void receiveResponse(final ResponseEnvelope<?> envelope) {
352 final long now = currentTime();
353 lastReceivedTicks = now;
355 final Optional<TransmittedConnectionEntry> maybeEntry;
358 maybeEntry = queue.complete(envelope, now);
363 if (maybeEntry.isPresent()) {
364 final TransmittedConnectionEntry entry = maybeEntry.get();
365 LOG.debug("Completing {} with {}", entry, envelope);
366 entry.complete(envelope.getMessage());
371 public final String toString() {
372 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
375 ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
376 return toStringHelper.add("client", context.getIdentifier()).add("cookie", cookie).add("poisoned", poisoned);