e1c5589004ec6685b086efacc32972d890516d8b
[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         @Override
56         int canTransmitCount(final int inflightSize) {
57             return 0;
58         }
59
60         @Override
61         TransmittedConnectionEntry transmit(final ConnectionEntry entry, final long now) {
62             throw new UnsupportedOperationException("Attempted to transmit on a halted queue");
63         }
64     }
65
66     static final class Transmitting extends TransmitQueue {
67         private final BackendInfo backend;
68         private long nextTxSequence;
69
70         Transmitting(final BackendInfo backend) {
71             this.backend = Preconditions.checkNotNull(backend);
72         }
73
74         @Override
75         int canTransmitCount(final int inflightSize) {
76             return backend.getMaxMessages() - inflightSize;
77         }
78
79         @Override
80         TransmittedConnectionEntry transmit(final ConnectionEntry entry, final long now) {
81             final RequestEnvelope env = new RequestEnvelope(entry.getRequest().toVersion(backend.getVersion()),
82                 backend.getSessionId(), nextTxSequence++);
83
84             final TransmittedConnectionEntry ret = new TransmittedConnectionEntry(entry, env.getSessionId(),
85                 env.getTxSequence(), now);
86             backend.getActor().tell(env, ActorRef.noSender());
87             return ret;
88         }
89     }
90
91     private static final Logger LOG = LoggerFactory.getLogger(TransmitQueue.class);
92
93     private final ArrayDeque<TransmittedConnectionEntry> inflight = new ArrayDeque<>();
94     private final ArrayDeque<ConnectionEntry> pending = new ArrayDeque<>();
95
96     private ReconnectForwarder successor;
97
98     final Iterable<ConnectionEntry> asIterable() {
99         return Iterables.concat(inflight, pending);
100     }
101
102     private void recordCompletion(final long now, final long enqueuedTicks, final long transmitTicks,
103             final long execNanos) {
104         // TODO: record
105     }
106
107     final Optional<TransmittedConnectionEntry> complete(final ResponseEnvelope<?> envelope, final long now) {
108         Optional<TransmittedConnectionEntry> maybeEntry = findMatchingEntry(inflight, envelope);
109         if (maybeEntry == null) {
110             LOG.debug("Request for {} not found in inflight queue, checking pending queue", envelope);
111             maybeEntry = findMatchingEntry(pending, envelope);
112         }
113
114         if (maybeEntry == null || !maybeEntry.isPresent()) {
115             LOG.warn("No request matching {} found, ignoring response", envelope);
116             return Optional.empty();
117         }
118
119         final TransmittedConnectionEntry entry = maybeEntry.get();
120         recordCompletion(now, entry.getEnqueuedTicks(), entry.getTxTicks(), envelope.getExecutionTimeNanos());
121
122         // We have freed up a slot, try to transmit something
123         int toSend = canTransmitCount(inflight.size());
124         while (toSend > 0) {
125             final ConnectionEntry e = pending.poll();
126             if (e == null) {
127                 break;
128             }
129
130             LOG.debug("Transmitting entry {}", e);
131             transmit(e, now);
132             toSend--;
133         }
134
135         return Optional.of(entry);
136     }
137
138     final void enqueue(final ConnectionEntry entry, final long now) {
139         if (successor != null) {
140             successor.forwardEntry(entry, now);
141             return;
142         }
143
144         if (canTransmitCount(inflight.size()) <= 0) {
145             LOG.trace("Queue is at capacity, delayed sending of request {}", entry.getRequest());
146             pending.add(entry);
147             return;
148         }
149
150         // We are not thread-safe and are supposed to be externally-guarded, hence send-before-record should be fine.
151         // This needs to be revisited if the external guards are lowered.
152         inflight.offer(transmit(entry, now));
153         LOG.debug("Sent request {} on queue {}", entry.getRequest(), this);
154     }
155
156     abstract int canTransmitCount(int inflightSize);
157
158     abstract TransmittedConnectionEntry transmit(ConnectionEntry entry, long now);
159
160     final boolean isEmpty() {
161         return inflight.isEmpty() && pending.isEmpty();
162     }
163
164     final ConnectionEntry peek() {
165         final ConnectionEntry ret = inflight.peek();
166         if (ret != null) {
167             return ret;
168         }
169
170         return pending.peek();
171     }
172
173     final void poison(final RequestException cause) {
174         poisonQueue(inflight, cause);
175         poisonQueue(pending, cause);
176     }
177
178     final void setForwarder(final ReconnectForwarder forwarder, final long now) {
179         Verify.verify(successor == null, "Successor {} already set on connection {}", successor, this);
180         successor = Preconditions.checkNotNull(forwarder);
181         LOG.debug("Connection {} superseded by {}, splicing queue", this, successor);
182
183         ConnectionEntry entry = inflight.poll();
184         while (entry != null) {
185             successor.forwardEntry(entry, now);
186             entry = inflight.poll();
187         }
188
189         entry = pending.poll();
190         while (entry != null) {
191             successor.forwardEntry(entry, now);
192             entry = pending.poll();
193         }
194     }
195
196     /*
197      * We are using tri-state return here to indicate one of three conditions:
198      * - if a matching entry is found, return an Optional containing it
199      * - if a matching entry is not found, but it makes sense to keep looking at other queues, return null
200      * - if a conflicting entry is encountered, indicating we should ignore this request, return an empty Optional
201      */
202     @SuppressFBWarnings(value = "NP_OPTIONAL_RETURN_NULL",
203             justification = "Returning null Optional is documented in the API contract.")
204     private static Optional<TransmittedConnectionEntry> findMatchingEntry(final Queue<? extends ConnectionEntry> queue,
205             final ResponseEnvelope<?> envelope) {
206         // Try to find the request in a queue. Responses may legally come back in a different order, hence we need
207         // to use an iterator
208         final Iterator<? extends ConnectionEntry> it = queue.iterator();
209         while (it.hasNext()) {
210             final ConnectionEntry e = it.next();
211             final Request<?, ?> request = e.getRequest();
212             final Response<?, ?> response = envelope.getMessage();
213
214             // First check for matching target, or move to next entry
215             if (!request.getTarget().equals(response.getTarget())) {
216                 continue;
217             }
218
219             // Sanity-check logical sequence, ignore any out-of-order messages
220             if (request.getSequence() != response.getSequence()) {
221                 LOG.debug("Expecting sequence {}, ignoring response {}", request.getSequence(), envelope);
222                 return Optional.empty();
223             }
224
225             // Check if the entry has (ever) been transmitted
226             if (!(e instanceof TransmittedConnectionEntry)) {
227                 return Optional.empty();
228             }
229
230             final TransmittedConnectionEntry te = (TransmittedConnectionEntry) e;
231
232             // Now check session match
233             if (envelope.getSessionId() != te.getSessionId()) {
234                 LOG.debug("Expecting session {}, ignoring response {}", te.getSessionId(), envelope);
235                 return Optional.empty();
236             }
237             if (envelope.getTxSequence() != te.getTxSequence()) {
238                 LOG.warn("Expecting txSequence {}, ignoring response {}", te.getTxSequence(), envelope);
239                 return Optional.empty();
240             }
241
242             LOG.debug("Completing request {} with {}", request, envelope);
243             it.remove();
244             return Optional.of(te);
245         }
246
247         return null;
248     }
249
250     private static void poisonQueue(final Queue<? extends ConnectionEntry> queue, final RequestException cause) {
251         for (ConnectionEntry e : queue) {
252             final Request<?, ?> request = e.getRequest();
253             LOG.trace("Poisoning request {}", request, cause);
254             e.complete(request.toRequestFailure(cause));
255         }
256         queue.clear();
257     }
258
259 }