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.Iterator;
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 Iterable<ConnectionEntry> startReplay() {
161 return queue.asIterable();
165 final void finishReplay(final ReconnectForwarder forwarder) {
166 queue.setForwarder(forwarder);
171 final void setForwarder(final ReconnectForwarder forwarder) {
172 final long now = currentTime();
173 final Iterator<ConnectionEntry> it = queue.asIterable().iterator();
174 while (it.hasNext()) {
175 final ConnectionEntry e = it.next();
176 forwarder.forwardEntry(e, now);
180 queue.setForwarder(forwarder);
184 abstract ClientActorBehavior<T> lockedReconnect(ClientActorBehavior<T> current);
186 final long enqueueEntry(final ConnectionEntry entry, final long now) {
189 final RequestException maybePoison = poisoned;
190 if (maybePoison != null) {
191 throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
194 if (queue.isEmpty()) {
195 // The queue is becoming non-empty, schedule a timer.
196 scheduleTimer(entry.getEnqueuedTicks() + REQUEST_TIMEOUT_NANOS - now);
198 return queue.enqueue(entry, now);
204 final ClientActorBehavior<T> reconnect(final ClientActorBehavior<T> current) {
207 return lockedReconnect(current);
214 * Schedule a timer to fire on the actor thread after a delay.
216 * @param delay Delay, in nanoseconds
219 private void scheduleTimer(final long delay) {
221 LOG.debug("{}: timer already scheduled", context.persistenceId());
224 if (queue.hasSuccessor()) {
225 LOG.debug("{}: connection has successor, not scheduling timer", context.persistenceId());
229 // If the delay is negative, we need to schedule an action immediately. While the caller could have checked
230 // for that condition and take appropriate action, but this is more convenient and less error-prone.
231 final long normalized = delay <= 0 ? 0 : Math.min(delay, BACKEND_ALIVE_TIMEOUT_NANOS);
233 final FiniteDuration dur = FiniteDuration.fromNanos(normalized);
234 LOG.debug("{}: scheduling timeout in {}", context.persistenceId(), dur);
235 context.executeInActor(this::runTimer, dur);
240 * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
241 * in {@link #NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
243 * @param current Current behavior
244 * @return Next behavior to use
247 final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
248 final Optional<Long> delay;
253 final long now = currentTime();
254 // The following line is only reliable when queue is not forwarding, but such state should not last long.
255 // FIXME: BUG-8422: this may not be accurate w.r.t. replayed entries
256 final long ticksSinceProgress = queue.ticksStalling(now);
257 if (ticksSinceProgress >= NO_PROGRESS_TIMEOUT_NANOS) {
258 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
259 TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
261 lockedPoison(new NoProgressException(ticksSinceProgress));
262 current.removeConnection(this);
266 // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
267 // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
268 // return convention.
269 delay = lockedCheckTimeout(now);
271 // We have timed out. There is no point in scheduling a timer
272 return lockedReconnect(current);
275 if (delay.isPresent()) {
276 // If there is new delay, schedule a timer
277 scheduleTimer(delay.get());
287 final Optional<Long> checkTimeout(final long now) {
290 return lockedCheckTimeout(now);
297 * We are using tri-state return here to indicate one of three conditions:
298 * - if there is no timeout to schedule, return Optional.empty()
299 * - if there is a timeout to schedule, return a non-empty optional
300 * - if this connections has timed out, return null
302 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
303 justification = "Returning null Optional is documented in the API contract.")
305 private Optional<Long> lockedCheckTimeout(final long now) {
306 if (queue.isEmpty()) {
307 return Optional.empty();
310 final long backendSilentTicks = now - lastReceivedTicks;
311 if (backendSilentTicks >= BACKEND_ALIVE_TIMEOUT_NANOS) {
312 LOG.debug("Connection {} has not seen activity from backend for {} nanoseconds, timing out", this,
317 int tasksTimedOut = 0;
318 for (ConnectionEntry head = queue.peek(); head != null; head = queue.peek()) {
319 final long beenOpen = now - head.getEnqueuedTicks();
320 if (beenOpen < REQUEST_TIMEOUT_NANOS) {
321 return Optional.of(REQUEST_TIMEOUT_NANOS - beenOpen);
326 LOG.debug("Connection {} timed out entryt {}", this, head);
327 head.complete(head.getRequest().toRequestFailure(
328 new RequestTimeoutException("Timed out after " + beenOpen + "ns")));
331 LOG.debug("Connection {} timed out {} tasks", this, tasksTimedOut);
332 if (tasksTimedOut != 0) {
333 queue.tryTransmit(now);
336 return Optional.empty();
339 final void poison(final RequestException cause) {
349 private void lockedPoison(final RequestException cause) {
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);