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);
43 // Keep these constants in nanoseconds, as that prevents unnecessary conversions in the fast path
45 static final long NO_PROGRESS_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(15);
47 static final long REQUEST_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(30);
49 private static final FiniteDuration REQUEST_TIMEOUT_DURATION = FiniteDuration.apply(REQUEST_TIMEOUT_NANOS,
50 TimeUnit.NANOSECONDS);
52 private final Lock lock = new ReentrantLock();
53 private final ClientActorContext context;
55 private final TransmitQueue queue;
56 private final Long cookie;
59 private boolean haveTimer;
61 private volatile RequestException poisoned;
63 // Do not allow subclassing outside of this package
64 AbstractClientConnection(final ClientActorContext context, final Long cookie,
65 final TransmitQueue queue) {
66 this.context = Preconditions.checkNotNull(context);
67 this.cookie = Preconditions.checkNotNull(cookie);
68 this.queue = Preconditions.checkNotNull(queue);
71 // Do not allow subclassing outside of this package
72 AbstractClientConnection(final AbstractClientConnection<T> oldConnection, final int targetQueueSize) {
73 this.context = oldConnection.context;
74 this.cookie = oldConnection.cookie;
75 this.queue = new TransmitQueue.Halted(targetQueueSize);
78 public final ClientActorContext context() {
82 public final @Nonnull Long cookie() {
86 public final ActorRef localActor() {
87 return context.self();
91 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
94 * <p>This method may put the caller thread to sleep in order to throttle the request rate.
95 * The callback may be called before the sleep finishes.
97 * @param request Request to send
98 * @param callback Callback to invoke
100 public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
101 final RequestException maybePoison = poisoned;
102 if (maybePoison != null) {
103 throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
106 final ConnectionEntry entry = new ConnectionEntry(request, callback, readTime());
107 enqueueAndWait(entry, entry.getEnqueuedTicks());
110 public abstract Optional<T> getBackendInfo();
112 final Iterable<ConnectionEntry> startReplay() {
114 return queue.asIterable();
118 final void finishReplay(final ReconnectForwarder forwarder) {
119 setForwarder(forwarder);
124 final void setForwarder(final ReconnectForwarder forwarder) {
125 queue.setForwarder(forwarder, readTime());
129 abstract ClientActorBehavior<T> lockedReconnect(ClientActorBehavior<T> current);
131 private long readTime() {
132 return context.ticker().read();
135 final long enqueueEntry(final ConnectionEntry entry, final long now) {
138 if (queue.isEmpty()) {
139 // The queue is becoming non-empty, schedule a timer
140 scheduleTimer(REQUEST_TIMEOUT_DURATION);
142 return queue.enqueue(entry, now);
148 final void enqueueAndWait(final ConnectionEntry entry, final long now) {
149 final long delay = enqueueEntry(entry, now);
151 TimeUnit.NANOSECONDS.sleep(delay);
152 } catch (InterruptedException e) {
153 LOG.debug("Interrupted while sleeping", e);
157 final ClientActorBehavior<T> reconnect(final ClientActorBehavior<T> current) {
160 return lockedReconnect(current);
167 * Schedule a timer to fire on the actor thread after a delay.
169 * @param delay Delay, in nanoseconds
172 private void scheduleTimer(final FiniteDuration delay) {
174 LOG.debug("{}: timer already scheduled", context.persistenceId());
177 if (queue.hasSuccessor()) {
178 LOG.debug("{}: connection has successor, not scheduling timer", context.persistenceId());
181 LOG.debug("{}: scheduling timeout in {}", context.persistenceId(), delay);
182 context.executeInActor(this::runTimer, delay);
187 * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
188 * in {@link #NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
190 * @param current Current behavior
191 * @return Next behavior to use
194 final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
195 final Optional<FiniteDuration> delay;
200 final long now = readTime();
201 // The following line is only reliable when queue is not forwarding, but such state should not last long.
202 final long ticksSinceProgress = queue.ticksStalling(now);
203 if (ticksSinceProgress >= NO_PROGRESS_TIMEOUT_NANOS) {
204 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
205 TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
207 lockedPoison(new NoProgressException(ticksSinceProgress));
208 current.removeConnection(this);
212 // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
213 // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
214 // return convention.
215 delay = lockedCheckTimeout(now);
217 // We have timed out. There is no point in scheduling a timer
218 return lockedReconnect(current);
221 if (delay.isPresent()) {
222 // If there is new delay, schedule a timer
223 scheduleTimer(delay.get());
233 final Optional<FiniteDuration> checkTimeout(final long now) {
236 return lockedCheckTimeout(now);
243 * We are using tri-state return here to indicate one of three conditions:
244 * - if there is no timeout to schedule, return Optional.empty()
245 * - if there is a timeout to schedule, return a non-empty optional
246 * - if this connections has timed out, return null
248 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
249 justification = "Returning null Optional is documented in the API contract.")
251 private Optional<FiniteDuration> lockedCheckTimeout(final long now) {
252 final ConnectionEntry head = queue.peek();
254 return Optional.empty();
257 final long beenOpen = now - head.getEnqueuedTicks();
258 if (beenOpen >= REQUEST_TIMEOUT_NANOS) {
259 LOG.debug("Connection {} has a request not completed for {} nanoseconds, timing out", this, beenOpen);
263 return Optional.of(FiniteDuration.apply(REQUEST_TIMEOUT_NANOS - beenOpen, TimeUnit.NANOSECONDS));
266 final void poison(final RequestException cause) {
276 private void lockedPoison(final RequestException cause) {
282 final RequestException poisoned() {
286 final void receiveResponse(final ResponseEnvelope<?> envelope) {
287 final long now = readTime();
289 final Optional<TransmittedConnectionEntry> maybeEntry;
292 maybeEntry = queue.complete(envelope, now);
297 if (maybeEntry.isPresent()) {
298 final TransmittedConnectionEntry entry = maybeEntry.get();
299 LOG.debug("Completing {} with {}", entry, envelope);
300 entry.complete(envelope.getMessage());
305 public final String toString() {
306 return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
309 ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
310 return toStringHelper.add("client", context.getIdentifier()).add("cookie", cookie).add("poisoned", poisoned);