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