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