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