Make AbstractClientConnection timeouts configurable
[controller.git] / opendaylight / md-sal / cds-access-client / src / main / java / org / opendaylight / controller / cluster / access / client / AbstractClientConnection.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.access.client;
9
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;
34
35 /**
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.
39  *
40  * @author Robert Varga
41  */
42 @NotThreadSafe
43 public abstract class AbstractClientConnection<T extends BackendInfo> {
44     private static final Logger LOG = LoggerFactory.getLogger(AbstractClientConnection.class);
45
46     /*
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
49      * path.
50      */
51     /**
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 attempt to reconnect
54      * it.
55      */
56     public static final long DEFAULT_BACKEND_ALIVE_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(30);
57
58     /**
59      * Request timeout. If the request fails to complete within this time since it was originally enqueued, we time
60      * the request out.
61      */
62     public static final long DEFAULT_REQUEST_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(2);
63
64     /**
65      * No progress timeout. A client fails to make any forward progress in this time, it will terminate itself.
66      */
67     public static final long DEFAULT_NO_PROGRESS_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(15);
68
69     // Emit a debug entry if we sleep for more that this amount
70     private static final long DEBUG_DELAY_NANOS = TimeUnit.MILLISECONDS.toNanos(100);
71
72     // Upper bound on the time a thread is forced to sleep to keep queue size under control
73     private static final long MAX_DELAY_SECONDS = 5;
74     private static final long MAX_DELAY_NANOS = TimeUnit.SECONDS.toNanos(MAX_DELAY_SECONDS);
75
76     private final Lock lock = new ReentrantLock();
77     private final ClientActorContext context;
78     @GuardedBy("lock")
79     private final TransmitQueue queue;
80     private final Long cookie;
81
82     @GuardedBy("lock")
83     private boolean haveTimer;
84
85     /**
86      * Time reference when we saw any activity from the backend.
87      */
88     private long lastReceivedTicks;
89
90     private volatile RequestException poisoned;
91
92     // Do not allow subclassing outside of this package
93     AbstractClientConnection(final ClientActorContext context, final Long cookie,
94             final TransmitQueue queue) {
95         this.context = Preconditions.checkNotNull(context);
96         this.cookie = Preconditions.checkNotNull(cookie);
97         this.queue = Preconditions.checkNotNull(queue);
98         this.lastReceivedTicks = currentTime();
99     }
100
101     // Do not allow subclassing outside of this package
102     AbstractClientConnection(final AbstractClientConnection<T> oldConnection, final int targetQueueSize) {
103         this.context = oldConnection.context;
104         this.cookie = oldConnection.cookie;
105         this.queue = new TransmitQueue.Halted(targetQueueSize);
106         this.lastReceivedTicks = oldConnection.lastReceivedTicks;
107     }
108
109     public final ClientActorContext context() {
110         return context;
111     }
112
113     public final @Nonnull Long cookie() {
114         return cookie;
115     }
116
117     public final ActorRef localActor() {
118         return context.self();
119     }
120
121     public final long currentTime() {
122         return context.ticker().read();
123     }
124
125     /**
126      * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
127      * from any thread.
128      *
129      * <p>This method may put the caller thread to sleep in order to throttle the request rate.
130      * The callback may be called before the sleep finishes.
131      *
132      * @param request Request to send
133      * @param callback Callback to invoke
134      */
135     public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
136         final long now = currentTime();
137         sendEntry(new ConnectionEntry(request, callback, now), now);
138     }
139
140     /**
141      * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
142      * from any thread.
143      *
144      * <p>
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.
147      *
148      * @param request Request to send
149      * @param callback Callback to invoke
150      * @param enqueuedTicks Time (according to {@link #currentTime()} of request enqueue
151      */
152     public final void enqueueRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback,
153             final long enqueuedTicks) {
154         enqueueEntry(new ConnectionEntry(request, callback, enqueuedTicks), currentTime());
155     }
156
157     public final long enqueueEntry(final ConnectionEntry entry, final long now) {
158         lock.lock();
159         try {
160             final RequestException maybePoison = poisoned;
161             if (maybePoison != null) {
162                 throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
163             }
164
165             if (queue.isEmpty()) {
166                 // The queue is becoming non-empty, schedule a timer.
167                 scheduleTimer(entry.getEnqueuedTicks() + context.config().getRequestTimeout() - now);
168             }
169             return queue.enqueue(entry, now);
170         } finally {
171             lock.unlock();
172         }
173     }
174
175     public abstract Optional<T> getBackendInfo();
176
177     final Collection<ConnectionEntry> startReplay() {
178         lock.lock();
179         return queue.drain();
180     }
181
182     @GuardedBy("lock")
183     final void finishReplay(final ReconnectForwarder forwarder) {
184         setForwarder(forwarder);
185
186         /*
187          * The process of replaying all messages may have taken a significant chunk of time, depending on type
188          * of messages, queue depth and available processing power. In extreme situations this may have already
189          * exceeded BACKEND_ALIVE_TIMEOUT_NANOS, in which case we are running the risk of not making reasonable forward
190          * progress before we start a reconnect cycle.
191          *
192          * Note that the timer is armed after we have sent the first message, hence we should be seeing a response
193          * from the backend before we see a timeout, simply due to how the mailbox operates.
194          *
195          * At any rate, reset the timestamp once we complete reconnection (which an atomic transition from the
196          * perspective of outside world), as that makes it a bit easier to reason about timing of events.
197          */
198         lastReceivedTicks = currentTime();
199         lock.unlock();
200     }
201
202     @GuardedBy("lock")
203     final void setForwarder(final ReconnectForwarder forwarder) {
204         queue.setForwarder(forwarder, currentTime());
205     }
206
207     @GuardedBy("lock")
208     abstract ClientActorBehavior<T> lockedReconnect(ClientActorBehavior<T> current,
209             RequestException runtimeRequestException);
210
211     final void sendEntry(final ConnectionEntry entry, final long now) {
212         long delay = enqueueEntry(entry, now);
213         try {
214             if (delay >= DEBUG_DELAY_NANOS) {
215                 if (delay > MAX_DELAY_NANOS) {
216                     LOG.info("Capping {} throttle delay from {} to {} seconds", this,
217                         TimeUnit.NANOSECONDS.toSeconds(delay), MAX_DELAY_SECONDS, new Throwable());
218                     delay = MAX_DELAY_NANOS;
219                 }
220                 if (LOG.isDebugEnabled()) {
221                     LOG.debug("{}: Sleeping for {}ms on connection {}", context.persistenceId(),
222                         TimeUnit.NANOSECONDS.toMillis(delay), this);
223                 }
224             }
225             TimeUnit.NANOSECONDS.sleep(delay);
226         } catch (InterruptedException e) {
227             Thread.currentThread().interrupt();
228             LOG.debug("Interrupted after sleeping {}ns", e, currentTime() - now);
229         }
230     }
231
232     final ClientActorBehavior<T> reconnect(final ClientActorBehavior<T> current, final RequestException cause) {
233         lock.lock();
234         try {
235             return lockedReconnect(current, cause);
236         } finally {
237             lock.unlock();
238         }
239     }
240
241     /**
242      * Schedule a timer to fire on the actor thread after a delay.
243      *
244      * @param delay Delay, in nanoseconds
245      */
246     @GuardedBy("lock")
247     private void scheduleTimer(final long delay) {
248         if (haveTimer) {
249             LOG.debug("{}: timer already scheduled on {}", context.persistenceId(), this);
250             return;
251         }
252         if (queue.hasSuccessor()) {
253             LOG.debug("{}: connection {} has a successor, not scheduling timer", context.persistenceId(), this);
254             return;
255         }
256
257         // If the delay is negative, we need to schedule an action immediately. While the caller could have checked
258         // for that condition and take appropriate action, but this is more convenient and less error-prone.
259         final long normalized =  delay <= 0 ? 0 : Math.min(delay, context.config().getBackendAlivenessTimerInterval());
260
261         final FiniteDuration dur = FiniteDuration.fromNanos(normalized);
262         LOG.debug("{}: connection {} scheduling timeout in {}", context.persistenceId(), this, dur);
263         context.executeInActor(this::runTimer, dur);
264         haveTimer = true;
265     }
266
267     /**
268      * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
269      * in {@link #DEFAULT_NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
270      *
271      * @param current Current behavior
272      * @return Next behavior to use
273      */
274     @VisibleForTesting
275     final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
276         final Optional<Long> delay;
277
278         lock.lock();
279         try {
280             haveTimer = false;
281             final long now = currentTime();
282
283             LOG.debug("{}: running timer on {}", context.persistenceId(), this);
284
285             // The following line is only reliable when queue is not forwarding, but such state should not last long.
286             // FIXME: BUG-8422: this may not be accurate w.r.t. replayed entries
287             final long ticksSinceProgress = queue.ticksStalling(now);
288             if (ticksSinceProgress >= context.config().getNoProgressTimeout()) {
289                 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
290                     TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
291
292                 lockedPoison(new NoProgressException(ticksSinceProgress));
293                 current.removeConnection(this);
294                 return current;
295             }
296
297             // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
298             // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
299             // return convention.
300             delay = lockedCheckTimeout(now);
301             if (delay == null) {
302                 // We have timed out. There is no point in scheduling a timer
303                 LOG.debug("{}: connection {} timed out", context.persistenceId(), this);
304                 return lockedReconnect(current, new RuntimeRequestException("Backend connection timed out",
305                     new TimeoutException()));
306             }
307
308             if (delay.isPresent()) {
309                 // If there is new delay, schedule a timer
310                 scheduleTimer(delay.get());
311             } else {
312                 LOG.debug("{}: not scheduling timeout on {}", context.persistenceId(), this);
313             }
314         } finally {
315             lock.unlock();
316         }
317
318         return current;
319     }
320
321     @VisibleForTesting
322     final Optional<Long> checkTimeout(final long now) {
323         lock.lock();
324         try {
325             return lockedCheckTimeout(now);
326         } finally {
327             lock.unlock();
328         }
329     }
330
331     long backendSilentTicks(final long now) {
332         return now - lastReceivedTicks;
333     }
334
335     /*
336      * We are using tri-state return here to indicate one of three conditions:
337      * - if there is no timeout to schedule, return Optional.empty()
338      * - if there is a timeout to schedule, return a non-empty optional
339      * - if this connections has timed out, return null
340      */
341     @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
342             justification = "Returning null Optional is documented in the API contract.")
343     @GuardedBy("lock")
344     private Optional<Long> lockedCheckTimeout(final long now) {
345         if (queue.isEmpty()) {
346             LOG.debug("{}: connection {} is empty", context.persistenceId(), this);
347             return Optional.empty();
348         }
349
350         final long backendSilentTicks = backendSilentTicks(now);
351         if (backendSilentTicks >= context.config().getBackendAlivenessTimerInterval()) {
352             LOG.debug("{}: Connection {} has not seen activity from backend for {} nanoseconds, timing out",
353                 context.persistenceId(), this, backendSilentTicks);
354             return null;
355         }
356
357         int tasksTimedOut = 0;
358         for (ConnectionEntry head = queue.peek(); head != null; head = queue.peek()) {
359             final long beenOpen = now - head.getEnqueuedTicks();
360             final long requestTimeout = context.config().getRequestTimeout();
361             if (beenOpen < requestTimeout) {
362                 return Optional.of(requestTimeout - beenOpen);
363             }
364
365             tasksTimedOut++;
366             queue.remove(now);
367             LOG.debug("{}: Connection {} timed out entry {}", context.persistenceId(), this, head);
368
369             final double time = beenOpen * 1.0 / 1_000_000_000;
370             head.complete(head.getRequest().toRequestFailure(
371                 new RequestTimeoutException("Timed out after " + time + "seconds")));
372         }
373
374         LOG.debug("Connection {} timed out {} tasks", this, tasksTimedOut);
375         if (tasksTimedOut != 0) {
376             queue.tryTransmit(now);
377         }
378
379         return Optional.empty();
380     }
381
382     final void poison(final RequestException cause) {
383         lock.lock();
384         try {
385             lockedPoison(cause);
386         } finally {
387             lock.unlock();
388         }
389     }
390
391     @GuardedBy("lock")
392     private void lockedPoison(final RequestException cause) {
393         poisoned = enrichPoison(cause);
394         queue.poison(cause);
395     }
396
397     RequestException enrichPoison(final RequestException ex) {
398         return ex;
399     }
400
401     @VisibleForTesting
402     final RequestException poisoned() {
403         return poisoned;
404     }
405
406     void receiveResponse(final ResponseEnvelope<?> envelope) {
407         final long now = currentTime();
408         lastReceivedTicks = now;
409
410         final Optional<TransmittedConnectionEntry> maybeEntry;
411         lock.lock();
412         try {
413             maybeEntry = queue.complete(envelope, now);
414         } finally {
415             lock.unlock();
416         }
417
418         if (maybeEntry.isPresent()) {
419             final TransmittedConnectionEntry entry = maybeEntry.get();
420             LOG.debug("Completing {} with {}", entry, envelope);
421             entry.complete(envelope.getMessage());
422         }
423     }
424
425     @Override
426     public final String toString() {
427         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
428     }
429
430     ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
431         return toStringHelper.add("client", context.getIdentifier()).add("cookie", cookie).add("poisoned", poisoned);
432     }
433 }