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