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