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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.