Bug 5280: Add ProgressTracker
[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 final Lock lock = new ReentrantLock();
48     private final ClientActorContext context;
49     @GuardedBy("lock")
50     private final TransmitQueue queue;
51     private final Long cookie;
52
53     private volatile RequestException poisoned;
54
55     // Do not allow subclassing outside of this package
56     AbstractClientConnection(final ClientActorContext context, final Long cookie,
57             final TransmitQueue queue) {
58         this.context = Preconditions.checkNotNull(context);
59         this.cookie = Preconditions.checkNotNull(cookie);
60         this.queue = Preconditions.checkNotNull(queue);
61     }
62
63     // Do not allow subclassing outside of this package
64     AbstractClientConnection(final AbstractClientConnection<T> oldConnection, final int targetQueueSize) {
65         this.context = oldConnection.context;
66         this.cookie = oldConnection.cookie;
67         this.queue = new TransmitQueue.Halted(targetQueueSize);
68     }
69
70     public final ClientActorContext context() {
71         return context;
72     }
73
74     public final @Nonnull Long cookie() {
75         return cookie;
76     }
77
78     public final ActorRef localActor() {
79         return context.self();
80     }
81
82     /**
83      * Send a request to the backend and invoke a specified callback when it finishes. This method is safe to invoke
84      * from any thread.
85      *
86      * <p>This method may put the caller thread to sleep in order to throttle the request rate.
87      * The callback may be called before the sleep finishes.
88      *
89      * @param request Request to send
90      * @param callback Callback to invoke
91      */
92     public final void sendRequest(final Request<?, ?> request, final Consumer<Response<?, ?>> callback) {
93         final RequestException maybePoison = poisoned;
94         if (maybePoison != null) {
95             throw new IllegalStateException("Connection " + this + " has been poisoned", maybePoison);
96         }
97
98         final ConnectionEntry entry = new ConnectionEntry(request, callback, readTime());
99         enqueueAndWait(entry, entry.getEnqueuedTicks());
100     }
101
102     public abstract Optional<T> getBackendInfo();
103
104     final Iterable<ConnectionEntry> startReplay() {
105         lock.lock();
106         return queue.asIterable();
107     }
108
109     @GuardedBy("lock")
110     final void finishReplay(final ReconnectForwarder forwarder) {
111         queue.setForwarder(forwarder, readTime());
112         lock.unlock();
113     }
114
115     @GuardedBy("lock")
116     final void setForwarder(final ReconnectForwarder forwarder) {
117         queue.setForwarder(forwarder, readTime());
118     }
119
120     @GuardedBy("lock")
121     abstract ClientActorBehavior<T> reconnectConnection(ClientActorBehavior<T> current);
122
123     private long readTime() {
124         return context.ticker().read();
125     }
126
127     final long enqueueEntry(final ConnectionEntry entry, final long now) {
128         lock.lock();
129         try {
130             return queue.enqueue(entry, now);
131         } finally {
132             lock.unlock();
133         }
134     }
135
136     final void enqueueAndWait(final ConnectionEntry entry, final long now) {
137         final long delay = enqueueEntry(entry, now);
138         try {
139             TimeUnit.NANOSECONDS.sleep(delay);
140         } catch (InterruptedException e) {
141             LOG.debug("Interrupted while sleeping");
142         }
143     }
144
145     /**
146      * Schedule a timer to fire on the actor thread after a delay.
147      *
148      * @param delay Delay, in nanoseconds
149      */
150     private void scheduleTimer(final FiniteDuration delay) {
151         LOG.debug("{}: scheduling timeout in {}", context.persistenceId(), delay);
152         context.executeInActor(this::runTimer, delay);
153     }
154
155     /**
156      * Check this queue for timeout and initiate reconnection if that happened. If the queue has not made progress
157      * in {@link #NO_PROGRESS_TIMEOUT_NANOS} nanoseconds, it will be aborted.
158      *
159      * @param current Current behavior
160      * @return Next behavior to use
161      */
162     @VisibleForTesting
163     final ClientActorBehavior<T> runTimer(final ClientActorBehavior<T> current) {
164         final Optional<FiniteDuration> delay;
165
166         lock.lock();
167         try {
168             final long now = readTime();
169             // The following line is only reliable when queue is not forwarding, but such state should not last long.
170             final long ticksSinceProgress = queue.ticksStalling(now);
171             if (ticksSinceProgress >= NO_PROGRESS_TIMEOUT_NANOS) {
172                 LOG.error("Queue {} has not seen progress in {} seconds, failing all requests", this,
173                     TimeUnit.NANOSECONDS.toSeconds(ticksSinceProgress));
174
175                 lockedPoison(new NoProgressException(ticksSinceProgress));
176                 current.removeConnection(this);
177                 return current;
178             }
179
180             // Requests are always scheduled in sequence, hence checking for timeout is relatively straightforward.
181             // Note we use also inquire about the delay, so we can re-schedule if needed, hence the unusual tri-state
182             // return convention.
183             delay = lockedCheckTimeout(now);
184             if (delay == null) {
185                 // We have timed out. There is no point in scheduling a timer
186                 return reconnectConnection(current);
187             }
188         } finally {
189             lock.unlock();
190         }
191
192         if (delay.isPresent()) {
193             // If there is new delay, schedule a timer
194             scheduleTimer(delay.get());
195         }
196
197         return current;
198     }
199
200     @VisibleForTesting
201     final Optional<FiniteDuration> checkTimeout(final long now) {
202         lock.lock();
203         try {
204             return lockedCheckTimeout(now);
205         } finally {
206             lock.unlock();
207         }
208     }
209
210     /*
211      * We are using tri-state return here to indicate one of three conditions:
212      * - if there is no timeout to schedule, return Optional.empty()
213      * - if there is a timeout to schedule, return a non-empty optional
214      * - if this connections has timed out, return null
215      */
216     @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
217             justification = "Returning null Optional is documented in the API contract.")
218     @GuardedBy("lock")
219     private Optional<FiniteDuration> lockedCheckTimeout(final long now) {
220         final ConnectionEntry head = queue.peek();
221         if (head == null) {
222             return Optional.empty();
223         }
224
225         final long beenOpen = now - head.getEnqueuedTicks();
226         if (beenOpen >= REQUEST_TIMEOUT_NANOS) {
227             LOG.debug("Connection {} has a request not completed for {} nanoseconds, timing out", this, beenOpen);
228             return null;
229         }
230
231         return Optional.of(FiniteDuration.apply(REQUEST_TIMEOUT_NANOS - beenOpen, TimeUnit.NANOSECONDS));
232     }
233
234     final void poison(final RequestException cause) {
235         lock.lock();
236         try {
237             lockedPoison(cause);
238         } finally {
239             lock.unlock();
240         }
241     }
242
243     @GuardedBy("lock")
244     private void lockedPoison(final RequestException cause) {
245         poisoned = cause;
246         queue.poison(cause);
247     }
248
249     @VisibleForTesting
250     final RequestException poisoned() {
251         return poisoned;
252     }
253
254     final void receiveResponse(final ResponseEnvelope<?> envelope) {
255         final long now = readTime();
256
257         final Optional<TransmittedConnectionEntry> maybeEntry;
258         lock.lock();
259         try {
260             maybeEntry = queue.complete(envelope, now);
261         } finally {
262             lock.unlock();
263         }
264
265         if (maybeEntry.isPresent()) {
266             final TransmittedConnectionEntry entry = maybeEntry.get();
267             LOG.debug("Completing {} with {}", entry, envelope);
268             entry.complete(envelope.getMessage());
269         }
270     }
271 }