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