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.Preconditions;
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import java.util.Optional;
15 import java.util.concurrent.TimeUnit;
16 import java.util.concurrent.locks.Lock;
17 import java.util.concurrent.locks.ReentrantLock;
18 import java.util.function.Consumer;
19 import javax.annotation.Nonnull;
20 import javax.annotation.concurrent.GuardedBy;
21 import javax.annotation.concurrent.NotThreadSafe;
22 import org.opendaylight.controller.cluster.access.concepts.Request;
23 import org.opendaylight.controller.cluster.access.concepts.RequestException;
24 import org.opendaylight.controller.cluster.access.concepts.Response;
25 import org.opendaylight.controller.cluster.access.concepts.ResponseEnvelope;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import scala.concurrent.duration.FiniteDuration;
31 * Base class for a connection to the backend. Responsible to queueing and dispatch of requests toward the backend.
32 * Can be in three conceptual states: Connecting, Connected and Reconnecting, which are represented by public final
33 * classes exposed from this package.
35 * @author Robert Varga
38 public abstract class AbstractClientConnection<T extends BackendInfo> {
39 private static final Logger LOG = LoggerFactory.getLogger(AbstractClientConnection.class);
41 // Keep these constants in nanoseconds, as that prevents unnecessary conversions in the fast path
43 static final long NO_PROGRESS_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(15);
45 static final long REQUEST_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(30);
47 private static final FiniteDuration REQUEST_TIMEOUT_DURATION = FiniteDuration.apply(REQUEST_TIMEOUT_NANOS,
48 TimeUnit.NANOSECONDS);
50 private final Lock lock = new ReentrantLock();
51 private final ClientActorContext context;
53 private final TransmitQueue queue;
54 private final Long cookie;
57 private boolean haveTimer;
59 private volatile RequestException poisoned;
61 // Do not allow subclassing outside of this package
62 AbstractClientConnection(final ClientActorContext context, final Long cookie,
63 final TransmitQueue queue) {
64 this.context = Preconditions.checkNotNull(context);
65 this.cookie = Preconditions.checkNotNull(cookie);
66 this.queue = Preconditions.checkNotNull(queue);
69 // Do not allow subclassing outside of this package
70 AbstractClientConnection(final AbstractClientConnection<T> oldConnection, final int targetQueueSize) {
71 this.context = oldConnection.context;
72 this.cookie = oldConnection.cookie;
73 this.queue = new TransmitQueue.Halted(targetQueueSize);
76 public final ClientActorContext context() {
80 public final @Nonnull Long cookie() {
84 public final ActorRef localActor() {
85 return context.self();
89 * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
92 * <p>This method may put the caller thread to sleep in order to throttle the request rate.
93 * The callback may be called before the sleep finishes.
95 * @param request Request to send
96 * @param callback Callback to invoke
98 public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
99 final RequestException maybePoison = poisoned;
100 if (maybePoison != null) {
101 throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
104 final ConnectionEntry entry = new ConnectionEntry(request, callback, readTime());
105 enqueueAndWait(entry, entry.getEnqueuedTicks());
108 public abstract Optional<T> getBackendInfo();
110 final Iterable<ConnectionEntry> startReplay() {
112 return queue.asIterable();
116 final void finishReplay(final ReconnectForwarder forwarder) {
117 setForwarder(forwarder);
122 final void setForwarder(final ReconnectForwarder forwarder) {
123 queue.setForwarder(forwarder, readTime());
127 abstract ClientActorBehavior<T> reconnectConnection(ClientActorBehavior<T> current);
129 private long readTime() {
130 return context.ticker().read();
133 final long enqueueEntry(final ConnectionEntry entry, final long now) {
136 if (queue.isEmpty()) {
137 // The queue is becoming non-empty, schedule a timer
138 scheduleTimer(REQUEST_TIMEOUT_DURATION);
140 return queue.enqueue(entry, now);
146 final void enqueueAndWait(final ConnectionEntry entry, final long now) {
147 final long delay = enqueueEntry(entry, now);
149 TimeUnit.NANOSECONDS.sleep(delay);
150 } catch (InterruptedException e) {
151 LOG.debug("Interrupted while sleeping", e);
156 * Schedule a timer to fire on the actor thread after a delay.
158 * @param delay Delay, in nanoseconds
161 private void scheduleTimer(final FiniteDuration delay) {
163 LOG.debug("{}: timer already scheduled", context.persistenceId());
166 if (queue.hasSuccessor()) {
167 LOG.debug("{}: connection has successor, not scheduling timer", context.persistenceId());
170 LOG.debug("{}: scheduling timeout in {}", context.persistenceId(), delay);
171 context.executeInActor(this::runTimer, delay);
176 * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
177 * in {@link #NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
179 * @param current Current behavior
180 * @return Next behavior to use
183 final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
184 final Optional<FiniteDuration> delay;
189 final long now = readTime();
190 // The following line is only reliable when queue is not forwarding, but such state should not last long.
191 final long ticksSinceProgress = queue.ticksStalling(now);
192 if (ticksSinceProgress >= NO_PROGRESS_TIMEOUT_NANOS) {
193 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
194 TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
196 lockedPoison(new NoProgressException(ticksSinceProgress));
197 current.removeConnection(this);
201 // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
202 // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
203 // return convention.
204 delay = lockedCheckTimeout(now);
206 // We have timed out. There is no point in scheduling a timer
207 return reconnectConnection(current);
210 if (delay.isPresent()) {
211 // If there is new delay, schedule a timer
212 scheduleTimer(delay.get());
222 final Optional<FiniteDuration> checkTimeout(final long now) {
225 return lockedCheckTimeout(now);
232 * We are using tri-state return here to indicate one of three conditions:
233 * - if there is no timeout to schedule, return Optional.empty()
234 * - if there is a timeout to schedule, return a non-empty optional
235 * - if this connections has timed out, return null
237 @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
238 justification = "Returning null Optional is documented in the API contract.")
240 private Optional<FiniteDuration> lockedCheckTimeout(final long now) {
241 final ConnectionEntry head = queue.peek();
243 return Optional.empty();
246 final long beenOpen = now - head.getEnqueuedTicks();
247 if (beenOpen >= REQUEST_TIMEOUT_NANOS) {
248 LOG.debug("Connection {} has a request not completed for {} nanoseconds, timing out", this, beenOpen);
252 return Optional.of(FiniteDuration.apply(REQUEST_TIMEOUT_NANOS - beenOpen, TimeUnit.NANOSECONDS));
255 final void poison(final RequestException cause) {
265 private void lockedPoison(final RequestException cause) {
271 final RequestException poisoned() {
275 final void receiveResponse(final ResponseEnvelope<?> envelope) {
276 final long now = readTime();
278 final Optional<TransmittedConnectionEntry> maybeEntry;
281 maybeEntry = queue.complete(envelope, now);
286 if (maybeEntry.isPresent()) {
287 final TransmittedConnectionEntry entry = maybeEntry.get();
288 LOG.debug("Completing {} with {}", entry, envelope);
289 entry.complete(envelope.getMessage());