4a1b3a2f293a499a64e805250a5a3776222caa67
[controller.git] / opendaylight / md-sal / cds-access-client / src / main / java / org / opendaylight / controller / cluster / access / client / TransmitQueue.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.base.Preconditions;
12 import com.google.common.base.Verify;
13 import com.google.common.collect.Iterables;
14 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
15 import java.util.ArrayDeque;
16 import java.util.Iterator;
17 import java.util.Optional;
18 import java.util.Queue;
19 import javax.annotation.concurrent.NotThreadSafe;
20 import org.opendaylight.controller.cluster.access.concepts.Request;
21 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
22 import org.opendaylight.controller.cluster.access.concepts.RequestException;
23 import org.opendaylight.controller.cluster.access.concepts.Response;
24 import org.opendaylight.controller.cluster.access.concepts.ResponseEnvelope;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 /**
29  * This queue is internally split into two queues for performance reasons, both memory efficiency and copy
30  * operations.
31  *
32  * <p>
33  * Entries are always appended to the end, but then they are transmitted to the remote end and do not necessarily
34  * complete in the order in which they were sent -- hence the head of the queue does not increase linearly,
35  * but can involve spurious removals of non-head entries.
36  *
37  * <p>
38  * For memory efficiency we want to pre-allocate both queues -- which points to ArrayDeque, but that is very
39  * inefficient when entries are removed from the middle. In the typical case we expect the number of in-flight
40  * entries to be an order of magnitude lower than the number of enqueued entries, hence the split.
41  *
42  * <p>
43  * Note that in transient case of reconnect, when the backend gives us a lower number of maximum in-flight entries
44  * than the previous incarnation, we may end up still moving the pending queue -- but that is a very exceptional
45  * scenario, hence we consciously ignore it to keep the design relatively simple.
46  *
47  * <p>
48  * This class is not thread-safe, as it is expected to be guarded by {@link AbstractClientConnection}.
49  *
50  * @author Robert Varga
51  */
52 @NotThreadSafe
53 abstract class TransmitQueue {
54     static final class Halted extends TransmitQueue {
55         Halted(final int targetDepth) {
56             super(targetDepth);
57         }
58
59         @Override
60         int canTransmitCount(final int inflightSize) {
61             return 0;
62         }
63
64         @Override
65         TransmittedConnectionEntry transmit(final ConnectionEntry entry, final long now) {
66             throw new UnsupportedOperationException("Attempted to transmit on a halted queue");
67         }
68     }
69
70     static final class Transmitting extends TransmitQueue {
71         private final BackendInfo backend;
72         private long nextTxSequence;
73
74         Transmitting(final int targetDepth, final BackendInfo backend) {
75             super(targetDepth);
76             this.backend = Preconditions.checkNotNull(backend);
77         }
78
79         @Override
80         int canTransmitCount(final int inflightSize) {
81             return backend.getMaxMessages() - inflightSize;
82         }
83
84         @Override
85         TransmittedConnectionEntry transmit(final ConnectionEntry entry, final long now) {
86             final RequestEnvelope env = new RequestEnvelope(entry.getRequest().toVersion(backend.getVersion()),
87                 backend.getSessionId(), nextTxSequence++);
88
89             final TransmittedConnectionEntry ret = new TransmittedConnectionEntry(entry, env.getSessionId(),
90                 env.getTxSequence(), now);
91             backend.getActor().tell(env, ActorRef.noSender());
92             return ret;
93         }
94     }
95
96     private static final Logger LOG = LoggerFactory.getLogger(TransmitQueue.class);
97
98     private final ArrayDeque<TransmittedConnectionEntry> inflight = new ArrayDeque<>();
99     private final ArrayDeque<ConnectionEntry> pending = new ArrayDeque<>();
100     private final ProgressTracker tracker;
101     private ReconnectForwarder successor;
102
103     TransmitQueue(final int targetDepth) {
104         tracker = new AveragingProgressTracker(targetDepth);
105     }
106
107     final Iterable<ConnectionEntry> asIterable() {
108         return Iterables.concat(inflight, pending);
109     }
110
111     final long ticksStalling(final long now) {
112         return tracker.ticksStalling(now);
113     }
114
115     // If a matching request was found, this will track a task was closed.
116     final Optional<TransmittedConnectionEntry> complete(final ResponseEnvelope<?> envelope, final long now) {
117         Optional<TransmittedConnectionEntry> maybeEntry = findMatchingEntry(inflight, envelope);
118         if (maybeEntry == null) {
119             LOG.debug("Request for {} not found in inflight queue, checking pending queue", envelope);
120             maybeEntry = findMatchingEntry(pending, envelope);
121         }
122
123         if (maybeEntry == null || !maybeEntry.isPresent()) {
124             LOG.warn("No request matching {} found, ignoring response", envelope);
125             return Optional.empty();
126         }
127
128         final TransmittedConnectionEntry entry = maybeEntry.get();
129         tracker.closeTask(now, entry.getEnqueuedTicks(), entry.getTxTicks(), envelope.getExecutionTimeNanos());
130
131         // We have freed up a slot, try to transmit something
132         int toSend = canTransmitCount(inflight.size());
133         while (toSend > 0) {
134             final ConnectionEntry e = pending.poll();
135             if (e == null) {
136                 break;
137             }
138
139             LOG.debug("Transmitting entry {}", e);
140             transmit(e, now);
141             toSend--;
142         }
143
144         return Optional.of(entry);
145     }
146
147     /**
148      * Enqueue an entry, possibly also transmitting it.
149      *
150      * @return Delay to be forced on the calling thread, in nanoseconds.
151      */
152     final long enqueue(final ConnectionEntry entry, final long now) {
153         if (successor != null) {
154             successor.forwardEntry(entry, now);
155             return 0;
156         }
157
158         // Reserve an entry before we do anything that can fail
159         final long delay = tracker.openTask(now);
160         if (canTransmitCount(inflight.size()) <= 0) {
161             LOG.trace("Queue is at capacity, delayed sending of request {}", entry.getRequest());
162             pending.add(entry);
163         } else {
164             // We are not thread-safe and are supposed to be externally-guarded,
165             // hence send-before-record should be fine.
166             // This needs to be revisited if the external guards are lowered.
167             inflight.offer(transmit(entry, now));
168             LOG.debug("Sent request {} on queue {}", entry.getRequest(), this);
169         }
170         return delay;
171     }
172
173     /**
174      * Return the number of entries which can be transmitted assuming the supplied in-flight queue size.
175      */
176     abstract int canTransmitCount(int inflightSize);
177
178     abstract TransmittedConnectionEntry transmit(ConnectionEntry entry, long now);
179
180     final boolean isEmpty() {
181         return inflight.isEmpty() && pending.isEmpty();
182     }
183
184     final ConnectionEntry peek() {
185         final ConnectionEntry ret = inflight.peek();
186         if (ret != null) {
187             return ret;
188         }
189
190         return pending.peek();
191     }
192
193     final void poison(final RequestException cause) {
194         poisonQueue(inflight, cause);
195         poisonQueue(pending, cause);
196     }
197
198     final void setForwarder(final ReconnectForwarder forwarder, final long now) {
199         Verify.verify(successor == null, "Successor {} already set on connection {}", successor, this);
200         successor = Preconditions.checkNotNull(forwarder);
201         LOG.debug("Connection {} superseded by {}, splicing queue", this, successor);
202
203         ConnectionEntry entry = inflight.poll();
204         while (entry != null) {
205             successor.forwardEntry(entry, now);
206             entry = inflight.poll();
207         }
208
209         entry = pending.poll();
210         while (entry != null) {
211             successor.forwardEntry(entry, now);
212             entry = pending.poll();
213         }
214     }
215
216     /*
217      * We are using tri-state return here to indicate one of three conditions:
218      * - if a matching entry is found, return an Optional containing it
219      * - if a matching entry is not found, but it makes sense to keep looking at other queues, return null
220      * - if a conflicting entry is encountered, indicating we should ignore this request, return an empty Optional
221      */
222     @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
223             justification = "Returning null Optional is documented in the API contract.")
224     private static Optional<TransmittedConnectionEntry> findMatchingEntry(final Queue<? extends ConnectionEntry> queue,
225             final ResponseEnvelope<?> envelope) {
226         // Try to find the request in a queue. Responses may legally come back in a different order, hence we need
227         // to use an iterator
228         final Iterator<? extends ConnectionEntry> it = queue.iterator();
229         while (it.hasNext()) {
230             final ConnectionEntry e = it.next();
231             final Request<?, ?> request = e.getRequest();
232             final Response<?, ?> response = envelope.getMessage();
233
234             // First check for matching target, or move to next entry
235             if (!request.getTarget().equals(response.getTarget())) {
236                 continue;
237             }
238
239             // Sanity-check logical sequence, ignore any out-of-order messages
240             if (request.getSequence() != response.getSequence()) {
241                 LOG.debug("Expecting sequence {}, ignoring response {}", request.getSequence(), envelope);
242                 return Optional.empty();
243             }
244
245             // Check if the entry has (ever) been transmitted
246             if (!(e instanceof TransmittedConnectionEntry)) {
247                 return Optional.empty();
248             }
249
250             final TransmittedConnectionEntry te = (TransmittedConnectionEntry) e;
251
252             // Now check session match
253             if (envelope.getSessionId() != te.getSessionId()) {
254                 LOG.debug("Expecting session {}, ignoring response {}", te.getSessionId(), envelope);
255                 return Optional.empty();
256             }
257             if (envelope.getTxSequence() != te.getTxSequence()) {
258                 LOG.warn("Expecting txSequence {}, ignoring response {}", te.getTxSequence(), envelope);
259                 return Optional.empty();
260             }
261
262             LOG.debug("Completing request {} with {}", request, envelope);
263             it.remove();
264             return Optional.of(te);
265         }
266
267         return null;
268     }
269
270     private static void poisonQueue(final Queue<? extends ConnectionEntry> queue, final RequestException cause) {
271         for (ConnectionEntry e : queue) {
272             final Request<?, ?> request = e.getRequest();
273             LOG.trace("Poisoning request {}", request, cause);
274             e.complete(request.toRequestFailure(cause));
275         }
276         queue.clear();
277     }
278
279 }