BUG-8422: separate retry and request timeouts
[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.Optional;
17 import java.util.concurrent.TimeUnit;
18 import java.util.concurrent.locks.Lock;
19 import java.util.concurrent.locks.ReentrantLock;
20 import java.util.function.Consumer;
21 import javax.annotation.Nonnull;
22 import javax.annotation.concurrent.GuardedBy;
23 import javax.annotation.concurrent.NotThreadSafe;
24 import org.opendaylight.controller.cluster.access.concepts.Request;
25 import org.opendaylight.controller.cluster.access.concepts.RequestException;
26 import org.opendaylight.controller.cluster.access.concepts.Response;
27 import org.opendaylight.controller.cluster.access.concepts.ResponseEnvelope;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30 import scala.concurrent.duration.FiniteDuration;
31
32 /**
33  * Base class for a connection to the backend. Responsible to queueing and dispatch of requests toward the backend.
34  * Can be in three conceptual states: Connecting, Connected and Reconnecting, which are represented by public final
35  * classes exposed from this package.
36  *
37  * @author Robert Varga
38  */
39 @NotThreadSafe
40 public abstract class AbstractClientConnection<T extends BackendInfo> {
41     private static final Logger LOG = LoggerFactory.getLogger(AbstractClientConnection.class);
42
43     /*
44      * Timers involved in communication with the backend. There are three tiers which are spaced out to allow for
45      * recovery at each tier. Keep these constants in nanoseconds, as that prevents unnecessary conversions in the fast
46      * path.
47      */
48     /**
49      * Backend aliveness timer. This is reset whenever we receive a response from the backend and kept armed whenever
50      * we have an outstanding request. If when this time expires, we tear down this connection and attept to reconnect
51      * it.
52      */
53     @VisibleForTesting
54     static final long BACKEND_ALIVE_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(30);
55
56     /**
57      * Request timeout. If the request fails to complete within this time since it was originally enqueued, we time
58      * the request out.
59      */
60     @VisibleForTesting
61     static final long REQUEST_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(2);
62
63     /**
64      * No progress timeout. A client fails to make any forward progress in this time, it will terminate itself.
65      */
66     @VisibleForTesting
67     static final long NO_PROGRESS_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(15);
68
69     private final Lock lock = new ReentrantLock();
70     private final ClientActorContext context;
71     @GuardedBy("lock")
72     private final TransmitQueue queue;
73     private final Long cookie;
74
75     @GuardedBy("lock")
76     private boolean haveTimer;
77
78     /**
79      * Time reference when we saw any activity from the backend.
80      */
81     private long lastReceivedTicks;
82
83     private volatile RequestException poisoned;
84
85     // Do not allow subclassing outside of this package
86     AbstractClientConnection(final ClientActorContext context, final Long cookie,
87             final TransmitQueue queue) {
88         this.context = Preconditions.checkNotNull(context);
89         this.cookie = Preconditions.checkNotNull(cookie);
90         this.queue = Preconditions.checkNotNull(queue);
91         this.lastReceivedTicks = currentTime();
92     }
93
94     // Do not allow subclassing outside of this package
95     AbstractClientConnection(final AbstractClientConnection<T> oldConnection, final int targetQueueSize) {
96         this.context = oldConnection.context;
97         this.cookie = oldConnection.cookie;
98         this.queue = new TransmitQueue.Halted(targetQueueSize);
99         this.lastReceivedTicks = oldConnection.lastReceivedTicks;
100     }
101
102     public final ClientActorContext context() {
103         return context;
104     }
105
106     public final @Nonnull Long cookie() {
107         return cookie;
108     }
109
110     public final ActorRef localActor() {
111         return context.self();
112     }
113
114     public final long currentTime() {
115         return context.ticker().read();
116     }
117
118     /**
119      * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
120      * from any thread.
121      *
122      * <p>This method may put the caller thread to sleep in order to throttle the request rate.
123      * The callback may be called before the sleep finishes.
124      *
125      * @param request Request to send
126      * @param callback Callback to invoke
127      */
128     public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
129         final long now = currentTime();
130         final long delay = enqueueEntry(new ConnectionEntry(request, callback, now), now);
131         try {
132             TimeUnit.NANOSECONDS.sleep(delay);
133         } catch (InterruptedException e) {
134             Thread.currentThread().interrupt();
135             LOG.debug("Interrupted after sleeping {}ns", e, currentTime() - now);
136         }
137     }
138
139     /**
140      * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
141      * from any thread.
142      *
143      * <p>
144      * Note that unlike {@link #sendRequest(Request, Consumer)}, this method does not exert backpressure, hence it
145      * should never be called from an application thread.
146      *
147      * @param request Request to send
148      * @param callback Callback to invoke
149      * @param enqueuedTicks Time (according to {@link #currentTime()} of request enqueue
150      */
151     public final void enqueueRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback,
152             final long enqueuedTicks) {
153         enqueueEntry(new ConnectionEntry(request, callback, enqueuedTicks), currentTime());
154     }
155
156     public abstract Optional<T> getBackendInfo();
157
158     final Iterable<ConnectionEntry> startReplay() {
159         lock.lock();
160         return queue.asIterable();
161     }
162
163     @GuardedBy("lock")
164     final void finishReplay(final ReconnectForwarder forwarder) {
165         setForwarder(forwarder);
166         lock.unlock();
167     }
168
169     @GuardedBy("lock")
170     final void setForwarder(final ReconnectForwarder forwarder) {
171         queue.setForwarder(forwarder, currentTime());
172     }
173
174     @GuardedBy("lock")
175     abstract ClientActorBehavior<T> lockedReconnect(ClientActorBehavior<T> current);
176
177     final long enqueueEntry(final ConnectionEntry entry, final long now) {
178         lock.lock();
179         try {
180             final RequestException maybePoison = poisoned;
181             if (maybePoison != null) {
182                 throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
183             }
184
185             if (queue.isEmpty()) {
186                 // The queue is becoming non-empty, schedule a timer.
187                 scheduleTimer(entry.getEnqueuedTicks() + REQUEST_TIMEOUT_NANOS - now);
188             }
189             return queue.enqueue(entry, now);
190         } finally {
191             lock.unlock();
192         }
193     }
194
195     final ClientActorBehavior<T> reconnect(final ClientActorBehavior<T> current) {
196         lock.lock();
197         try {
198             return lockedReconnect(current);
199         } finally {
200             lock.unlock();
201         }
202     }
203
204     /**
205      * Schedule a timer to fire on the actor thread after a delay.
206      *
207      * @param delay Delay, in nanoseconds
208      */
209     @GuardedBy("lock")
210     private void scheduleTimer(final long delay) {
211         if (haveTimer) {
212             LOG.debug("{}: timer already scheduled", context.persistenceId());
213             return;
214         }
215         if (queue.hasSuccessor()) {
216             LOG.debug("{}: connection has successor, not scheduling timer", context.persistenceId());
217             return;
218         }
219
220         // If the delay is negative, we need to schedule an action immediately. While the caller could have checked
221         // for that condition and take appropriate action, but this is more convenient and less error-prone.
222         final long normalized =  delay <= 0 ? 0 : Math.min(delay, BACKEND_ALIVE_TIMEOUT_NANOS);
223
224         final FiniteDuration dur = FiniteDuration.fromNanos(normalized);
225         LOG.debug("{}: scheduling timeout in {}", context.persistenceId(), dur);
226         context.executeInActor(this::runTimer, dur);
227         haveTimer = true;
228     }
229
230     /**
231      * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
232      * in {@link #NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
233      *
234      * @param current Current behavior
235      * @return Next behavior to use
236      */
237     @VisibleForTesting
238     final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
239         final Optional<Long> delay;
240
241         lock.lock();
242         try {
243             haveTimer = false;
244             final long now = currentTime();
245             // The following line is only reliable when queue is not forwarding, but such state should not last long.
246             // FIXME: BUG-8422: this may not be accurate w.r.t. replayed entries
247             final long ticksSinceProgress = queue.ticksStalling(now);
248             if (ticksSinceProgress >= NO_PROGRESS_TIMEOUT_NANOS) {
249                 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
250                     TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
251
252                 lockedPoison(new NoProgressException(ticksSinceProgress));
253                 current.removeConnection(this);
254                 return current;
255             }
256
257             // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
258             // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
259             // return convention.
260             delay = lockedCheckTimeout(now);
261             if (delay == null) {
262                 // We have timed out. There is no point in scheduling a timer
263                 return lockedReconnect(current);
264             }
265
266             if (delay.isPresent()) {
267                 // If there is new delay, schedule a timer
268                 scheduleTimer(delay.get());
269             }
270         } finally {
271             lock.unlock();
272         }
273
274         return current;
275     }
276
277     @VisibleForTesting
278     final Optional<Long> checkTimeout(final long now) {
279         lock.lock();
280         try {
281             return lockedCheckTimeout(now);
282         } finally {
283             lock.unlock();
284         }
285     }
286
287     /*
288      * We are using tri-state return here to indicate one of three conditions:
289      * - if there is no timeout to schedule, return Optional.empty()
290      * - if there is a timeout to schedule, return a non-empty optional
291      * - if this connections has timed out, return null
292      */
293     @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
294             justification = "Returning null Optional is documented in the API contract.")
295     @GuardedBy("lock")
296     private Optional<Long> lockedCheckTimeout(final long now) {
297         if (queue.isEmpty()) {
298             return Optional.empty();
299         }
300
301         final long backendSilentTicks = now - lastReceivedTicks;
302         if (backendSilentTicks >= BACKEND_ALIVE_TIMEOUT_NANOS) {
303             LOG.debug("Connection {} has not seen activity from backend for {} nanoseconds, timing out", this,
304                 backendSilentTicks);
305             return null;
306         }
307
308         int tasksTimedOut = 0;
309         for (ConnectionEntry head = queue.peek(); head != null; head = queue.peek()) {
310             final long beenOpen = now - head.getEnqueuedTicks();
311             if (beenOpen < REQUEST_TIMEOUT_NANOS) {
312                 return Optional.of(REQUEST_TIMEOUT_NANOS - beenOpen);
313             }
314
315             tasksTimedOut++;
316             queue.remove(now);
317             LOG.debug("Connection {} timed out entryt {}", this, head);
318             head.complete(head.getRequest().toRequestFailure(
319                 new RequestTimeoutException("Timed out after " + beenOpen + "ns")));
320         }
321
322         LOG.debug("Connection {} timed out {} tasks", this, tasksTimedOut);
323         if (tasksTimedOut != 0) {
324             queue.tryTransmit(now);
325         }
326
327         return Optional.empty();
328     }
329
330     final void poison(final RequestException cause) {
331         lock.lock();
332         try {
333             lockedPoison(cause);
334         } finally {
335             lock.unlock();
336         }
337     }
338
339     @GuardedBy("lock")
340     private void lockedPoison(final RequestException cause) {
341         poisoned = cause;
342         queue.poison(cause);
343     }
344
345     @VisibleForTesting
346     final RequestException poisoned() {
347         return poisoned;
348     }
349
350     final void receiveResponse(final ResponseEnvelope<?> envelope) {
351         final long now = currentTime();
352         lastReceivedTicks = now;
353
354         final Optional<TransmittedConnectionEntry> maybeEntry;
355         lock.lock();
356         try {
357             maybeEntry = queue.complete(envelope, now);
358         } finally {
359             lock.unlock();
360         }
361
362         if (maybeEntry.isPresent()) {
363             final TransmittedConnectionEntry entry = maybeEntry.get();
364             LOG.debug("Completing {} with {}", entry, envelope);
365             entry.complete(envelope.getMessage());
366         }
367     }
368
369     @Override
370     public final String toString() {
371         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
372     }
373
374     ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
375         return toStringHelper.add("client", context.getIdentifier()).add("cookie", cookie).add("poisoned", poisoned);
376     }
377 }