BUG-8403: guard against ConcurrentModificationException
[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.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 Collection<ConnectionEntry> startReplay() {
160         lock.lock();
161         return queue.drain();
162     }
163
164     @GuardedBy("lock")
165     final void finishReplay(final ReconnectForwarder forwarder) {
166         setForwarder(forwarder);
167         lock.unlock();
168     }
169
170     @GuardedBy("lock")
171     final void setForwarder(final ReconnectForwarder forwarder) {
172         queue.setForwarder(forwarder, currentTime());
173     }
174
175     @GuardedBy("lock")
176     abstract ClientActorBehavior<T> lockedReconnect(ClientActorBehavior<T> current);
177
178     final long enqueueEntry(final ConnectionEntry entry, final long now) {
179         lock.lock();
180         try {
181             final RequestException maybePoison = poisoned;
182             if (maybePoison != null) {
183                 throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
184             }
185
186             if (queue.isEmpty()) {
187                 // The queue is becoming non-empty, schedule a timer.
188                 scheduleTimer(entry.getEnqueuedTicks() + REQUEST_TIMEOUT_NANOS - now);
189             }
190             return queue.enqueue(entry, now);
191         } finally {
192             lock.unlock();
193         }
194     }
195
196     final ClientActorBehavior<T> reconnect(final ClientActorBehavior<T> current) {
197         lock.lock();
198         try {
199             return lockedReconnect(current);
200         } finally {
201             lock.unlock();
202         }
203     }
204
205     /**
206      * Schedule a timer to fire on the actor thread after a delay.
207      *
208      * @param delay Delay, in nanoseconds
209      */
210     @GuardedBy("lock")
211     private void scheduleTimer(final long delay) {
212         if (haveTimer) {
213             LOG.debug("{}: timer already scheduled", context.persistenceId());
214             return;
215         }
216         if (queue.hasSuccessor()) {
217             LOG.debug("{}: connection has successor, not scheduling timer", context.persistenceId());
218             return;
219         }
220
221         // If the delay is negative, we need to schedule an action immediately. While the caller could have checked
222         // for that condition and take appropriate action, but this is more convenient and less error-prone.
223         final long normalized =  delay <= 0 ? 0 : Math.min(delay, BACKEND_ALIVE_TIMEOUT_NANOS);
224
225         final FiniteDuration dur = FiniteDuration.fromNanos(normalized);
226         LOG.debug("{}: scheduling timeout in {}", context.persistenceId(), dur);
227         context.executeInActor(this::runTimer, dur);
228         haveTimer = true;
229     }
230
231     /**
232      * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
233      * in {@link #NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
234      *
235      * @param current Current behavior
236      * @return Next behavior to use
237      */
238     @VisibleForTesting
239     final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
240         final Optional<Long> delay;
241
242         lock.lock();
243         try {
244             haveTimer = false;
245             final long now = currentTime();
246             // The following line is only reliable when queue is not forwarding, but such state should not last long.
247             // FIXME: BUG-8422: this may not be accurate w.r.t. replayed entries
248             final long ticksSinceProgress = queue.ticksStalling(now);
249             if (ticksSinceProgress >= NO_PROGRESS_TIMEOUT_NANOS) {
250                 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
251                     TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
252
253                 lockedPoison(new NoProgressException(ticksSinceProgress));
254                 current.removeConnection(this);
255                 return current;
256             }
257
258             // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
259             // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
260             // return convention.
261             delay = lockedCheckTimeout(now);
262             if (delay == null) {
263                 // We have timed out. There is no point in scheduling a timer
264                 return lockedReconnect(current);
265             }
266
267             if (delay.isPresent()) {
268                 // If there is new delay, schedule a timer
269                 scheduleTimer(delay.get());
270             }
271         } finally {
272             lock.unlock();
273         }
274
275         return current;
276     }
277
278     @VisibleForTesting
279     final Optional<Long> checkTimeout(final long now) {
280         lock.lock();
281         try {
282             return lockedCheckTimeout(now);
283         } finally {
284             lock.unlock();
285         }
286     }
287
288     /*
289      * We are using tri-state return here to indicate one of three conditions:
290      * - if there is no timeout to schedule, return Optional.empty()
291      * - if there is a timeout to schedule, return a non-empty optional
292      * - if this connections has timed out, return null
293      */
294     @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
295             justification = "Returning null Optional is documented in the API contract.")
296     @GuardedBy("lock")
297     private Optional<Long> lockedCheckTimeout(final long now) {
298         if (queue.isEmpty()) {
299             return Optional.empty();
300         }
301
302         final long backendSilentTicks = now - lastReceivedTicks;
303         if (backendSilentTicks >= BACKEND_ALIVE_TIMEOUT_NANOS) {
304             LOG.debug("Connection {} has not seen activity from backend for {} nanoseconds, timing out", this,
305                 backendSilentTicks);
306             return null;
307         }
308
309         int tasksTimedOut = 0;
310         for (ConnectionEntry head = queue.peek(); head != null; head = queue.peek()) {
311             final long beenOpen = now - head.getEnqueuedTicks();
312             if (beenOpen < REQUEST_TIMEOUT_NANOS) {
313                 return Optional.of(REQUEST_TIMEOUT_NANOS - beenOpen);
314             }
315
316             tasksTimedOut++;
317             queue.remove(now);
318             LOG.debug("Connection {} timed out entryt {}", this, head);
319             head.complete(head.getRequest().toRequestFailure(
320                 new RequestTimeoutException("Timed out after " + beenOpen + "ns")));
321         }
322
323         LOG.debug("Connection {} timed out {} tasks", this, tasksTimedOut);
324         if (tasksTimedOut != 0) {
325             queue.tryTransmit(now);
326         }
327
328         return Optional.empty();
329     }
330
331     final void poison(final RequestException cause) {
332         lock.lock();
333         try {
334             lockedPoison(cause);
335         } finally {
336             lock.unlock();
337         }
338     }
339
340     @GuardedBy("lock")
341     private void lockedPoison(final RequestException cause) {
342         poisoned = cause;
343         queue.poison(cause);
344     }
345
346     @VisibleForTesting
347     final RequestException poisoned() {
348         return poisoned;
349     }
350
351     final void receiveResponse(final ResponseEnvelope<?> envelope) {
352         final long now = currentTime();
353         lastReceivedTicks = now;
354
355         final Optional<TransmittedConnectionEntry> maybeEntry;
356         lock.lock();
357         try {
358             maybeEntry = queue.complete(envelope, now);
359         } finally {
360             lock.unlock();
361         }
362
363         if (maybeEntry.isPresent()) {
364             final TransmittedConnectionEntry entry = maybeEntry.get();
365             LOG.debug("Completing {} with {}", entry, envelope);
366             entry.complete(envelope.getMessage());
367         }
368     }
369
370     @Override
371     public final String toString() {
372         return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
373     }
374
375     ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
376         return toStringHelper.add("client", context.getIdentifier()).add("cookie", cookie).add("poisoned", poisoned);
377     }
378 }