BUG-5280: make sure we arm the request timer
[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.Preconditions;
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import java.util.Optional;
15 import java.util.concurrent.TimeUnit;
16 import java.util.concurrent.locks.Lock;
17 import java.util.concurrent.locks.ReentrantLock;
18 import java.util.function.Consumer;
19 import javax.annotation.Nonnull;
20 import javax.annotation.concurrent.GuardedBy;
21 import javax.annotation.concurrent.NotThreadSafe;
22 import org.opendaylight.controller.cluster.access.concepts.Request;
23 import org.opendaylight.controller.cluster.access.concepts.RequestException;
24 import org.opendaylight.controller.cluster.access.concepts.Response;
25 import org.opendaylight.controller.cluster.access.concepts.ResponseEnvelope;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import scala.concurrent.duration.FiniteDuration;
29
30 /**
31  * Base class for a connection to the backend. Responsible to queueing and dispatch of requests toward the backend.
32  * Can be in three conceptual states: Connecting, Connected and Reconnecting, which are represented by public final
33  * classes exposed from this package.
34  *
35  * @author Robert Varga
36  */
37 @NotThreadSafe
38 public abstract class AbstractClientConnection<T extends BackendInfo> {
39     private static final Logger LOG = LoggerFactory.getLogger(AbstractClientConnection.class);
40
41     // Keep these constants in nanoseconds, as that prevents unnecessary conversions in the fast path
42     @VisibleForTesting
43     static final long NO_PROGRESS_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(15);
44     @VisibleForTesting
45     static final long REQUEST_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(30);
46
47     private static final FiniteDuration REQUEST_TIMEOUT_DURATION = FiniteDuration.apply(REQUEST_TIMEOUT_NANOS,
48         TimeUnit.NANOSECONDS);
49
50     private final Lock lock = new ReentrantLock();
51     private final ClientActorContext context;
52     @GuardedBy("lock")
53     private final TransmitQueue queue;
54     private final Long cookie;
55
56     @GuardedBy("lock")
57     private boolean haveTimer;
58
59     private volatile RequestException poisoned;
60
61     // Do not allow subclassing outside of this package
62     AbstractClientConnection(final ClientActorContext context, final Long cookie,
63             final TransmitQueue queue) {
64         this.context = Preconditions.checkNotNull(context);
65         this.cookie = Preconditions.checkNotNull(cookie);
66         this.queue = Preconditions.checkNotNull(queue);
67     }
68
69     // Do not allow subclassing outside of this package
70     AbstractClientConnection(final AbstractClientConnection<T> oldConnection, final int targetQueueSize) {
71         this.context = oldConnection.context;
72         this.cookie = oldConnection.cookie;
73         this.queue = new TransmitQueue.Halted(targetQueueSize);
74     }
75
76     public final ClientActorContext context() {
77         return context;
78     }
79
80     public final @Nonnull Long cookie() {
81         return cookie;
82     }
83
84     public final ActorRef localActor() {
85         return context.self();
86     }
87
88     /**
89      * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
90      * from any thread.
91      *
92      * <p>This method may put the caller thread to sleep in order to throttle the request rate.
93      * The callback may be called before the sleep finishes.
94      *
95      * @param request Request to send
96      * @param callback Callback to invoke
97      */
98     public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
99         final RequestException maybePoison = poisoned;
100         if (maybePoison != null) {
101             throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
102         }
103
104         final ConnectionEntry entry = new ConnectionEntry(request, callback, readTime());
105         enqueueAndWait(entry, entry.getEnqueuedTicks());
106     }
107
108     public abstract Optional<T> getBackendInfo();
109
110     final Iterable<ConnectionEntry> startReplay() {
111         lock.lock();
112         return queue.asIterable();
113     }
114
115     @GuardedBy("lock")
116     final void finishReplay(final ReconnectForwarder forwarder) {
117         setForwarder(forwarder);
118         lock.unlock();
119     }
120
121     @GuardedBy("lock")
122     final void setForwarder(final ReconnectForwarder forwarder) {
123         queue.setForwarder(forwarder, readTime());
124     }
125
126     @GuardedBy("lock")
127     abstract ClientActorBehavior<T> reconnectConnection(ClientActorBehavior<T> current);
128
129     private long readTime() {
130         return context.ticker().read();
131     }
132
133     final long enqueueEntry(final ConnectionEntry entry, final long now) {
134         lock.lock();
135         try {
136             if (queue.isEmpty()) {
137                 // The queue is becoming non-empty, schedule a timer
138                 scheduleTimer(REQUEST_TIMEOUT_DURATION);
139             }
140             return queue.enqueue(entry, now);
141         } finally {
142             lock.unlock();
143         }
144     }
145
146     final void enqueueAndWait(final ConnectionEntry entry, final long now) {
147         final long delay = enqueueEntry(entry, now);
148         try {
149             TimeUnit.NANOSECONDS.sleep(delay);
150         } catch (InterruptedException e) {
151             LOG.debug("Interrupted while sleeping", e);
152         }
153     }
154
155     /**
156      * Schedule a timer to fire on the actor thread after a delay.
157      *
158      * @param delay Delay, in nanoseconds
159      */
160     @GuardedBy("lock")
161     private void scheduleTimer(final FiniteDuration delay) {
162         if (haveTimer) {
163             LOG.debug("{}: timer already scheduled", context.persistenceId());
164             return;
165         }
166         if (queue.hasSuccessor()) {
167             LOG.debug("{}: connection has successor, not scheduling timer", context.persistenceId());
168             return;
169         }
170         LOG.debug("{}: scheduling timeout in {}", context.persistenceId(), delay);
171         context.executeInActor(this::runTimer, delay);
172         haveTimer = true;
173     }
174
175     /**
176      * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
177      * in {@link #NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
178      *
179      * @param current Current behavior
180      * @return Next behavior to use
181      */
182     @VisibleForTesting
183     final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
184         final Optional<FiniteDuration> delay;
185
186         lock.lock();
187         try {
188             haveTimer = false;
189             final long now = readTime();
190             // The following line is only reliable when queue is not forwarding, but such state should not last long.
191             final long ticksSinceProgress = queue.ticksStalling(now);
192             if (ticksSinceProgress >= NO_PROGRESS_TIMEOUT_NANOS) {
193                 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
194                     TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
195
196                 lockedPoison(new NoProgressException(ticksSinceProgress));
197                 current.removeConnection(this);
198                 return current;
199             }
200
201             // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
202             // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
203             // return convention.
204             delay = lockedCheckTimeout(now);
205             if (delay == null) {
206                 // We have timed out. There is no point in scheduling a timer
207                 return reconnectConnection(current);
208             }
209
210             if (delay.isPresent()) {
211                 // If there is new delay, schedule a timer
212                 scheduleTimer(delay.get());
213             }
214         } finally {
215             lock.unlock();
216         }
217
218         return current;
219     }
220
221     @VisibleForTesting
222     final Optional<FiniteDuration> checkTimeout(final long now) {
223         lock.lock();
224         try {
225             return lockedCheckTimeout(now);
226         } finally {
227             lock.unlock();
228         }
229     }
230
231     /*
232      * We are using tri-state return here to indicate one of three conditions:
233      * - if there is no timeout to schedule, return Optional.empty()
234      * - if there is a timeout to schedule, return a non-empty optional
235      * - if this connections has timed out, return null
236      */
237     @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
238             justification = "Returning null Optional is documented in the API contract.")
239     @GuardedBy("lock")
240     private Optional<FiniteDuration> lockedCheckTimeout(final long now) {
241         final ConnectionEntry head = queue.peek();
242         if (head == null) {
243             return Optional.empty();
244         }
245
246         final long beenOpen = now - head.getEnqueuedTicks();
247         if (beenOpen >= REQUEST_TIMEOUT_NANOS) {
248             LOG.debug("Connection {} has a request not completed for {} nanoseconds, timing out", this, beenOpen);
249             return null;
250         }
251
252         return Optional.of(FiniteDuration.apply(REQUEST_TIMEOUT_NANOS - beenOpen, TimeUnit.NANOSECONDS));
253     }
254
255     final void poison(final RequestException cause) {
256         lock.lock();
257         try {
258             lockedPoison(cause);
259         } finally {
260             lock.unlock();
261         }
262     }
263
264     @GuardedBy("lock")
265     private void lockedPoison(final RequestException cause) {
266         poisoned = cause;
267         queue.poison(cause);
268     }
269
270     @VisibleForTesting
271     final RequestException poisoned() {
272         return poisoned;
273     }
274
275     final void receiveResponse(final ResponseEnvelope<?> envelope) {
276         final long now = readTime();
277
278         final Optional<TransmittedConnectionEntry> maybeEntry;
279         lock.lock();
280         try {
281             maybeEntry = queue.complete(envelope, now);
282         } finally {
283             lock.unlock();
284         }
285
286         if (maybeEntry.isPresent()) {
287             final TransmittedConnectionEntry entry = maybeEntry.get();
288             LOG.debug("Completing {} with {}", entry, envelope);
289             entry.complete(envelope.getMessage());
290         }
291     }
292 }