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