2 * Copyright (c) 2015 Pantheon Technologies s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.openflowjava.protocol.impl.core.connection;
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.util.concurrent.FutureCallback;
13 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
14 import javax.annotation.Nonnull;
15 import org.opendaylight.openflowjava.protocol.api.connection.DeviceRequestFailedException;
16 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
17 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueException;
18 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.Error;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
23 final class OutboundQueueImpl implements OutboundQueue {
24 private static final Logger LOG = LoggerFactory.getLogger(OutboundQueueImpl.class);
25 private static final AtomicIntegerFieldUpdater<OutboundQueueImpl> CURRENT_OFFSET_UPDATER =
26 AtomicIntegerFieldUpdater.newUpdater(OutboundQueueImpl.class, "reserveOffset");
27 private static final AtomicIntegerFieldUpdater<OutboundQueueImpl> BARRIER_OFFSET_UPDATER =
28 AtomicIntegerFieldUpdater.newUpdater(OutboundQueueImpl.class, "barrierOffset");
29 private final OutboundQueueManager<?> manager;
30 private final OutboundQueueEntry[] queue;
31 private final long baseXid;
32 private final long endXid;
33 private final int reserve;
35 // Updated concurrently
36 private volatile int barrierOffset = -1;
37 private volatile int reserveOffset = 0;
39 // Updated from Netty only
40 private int flushOffset;
41 private int completeCount;
42 private int lastBarrierOffset = -1;
44 OutboundQueueImpl(final OutboundQueueManager<?> manager, final long baseXid, final int maxQueue) {
46 * We use the last entry as an emergency should a timeout-triggered
47 * flush request race with normal users for the last entry in this
48 * queue. In that case the flush request will take the last entry and
49 * schedule a flush, which means that we will get around sending the
50 * message as soon as the user finishes the reservation.
52 Preconditions.checkArgument(maxQueue > 1);
53 this.baseXid = baseXid;
54 this.endXid = baseXid + maxQueue;
55 this.reserve = maxQueue - 1;
56 this.manager = Preconditions.checkNotNull(manager);
57 queue = new OutboundQueueEntry[maxQueue];
58 for (int i = 0; i < maxQueue; ++i) {
59 queue[i] = new OutboundQueueEntry();
63 private OutboundQueueImpl(final OutboundQueueManager<?> manager, final long baseXid, final OutboundQueueEntry[] queue) {
64 this.manager = Preconditions.checkNotNull(manager);
65 this.queue = Preconditions.checkNotNull(queue);
66 this.baseXid = baseXid;
67 this.endXid = baseXid + queue.length;
68 this.reserve = queue.length - 1;
69 for (OutboundQueueEntry element : queue) {
74 OutboundQueueImpl reuse(final long baseXid) {
75 return new OutboundQueueImpl(manager, baseXid, queue);
79 public Long reserveEntry() {
80 return reserveEntry(false);
84 public void commitEntry(final Long xid, final OfHeader message, final FutureCallback<OfHeader> callback) {
85 final int offset = (int)(xid - baseXid);
86 if (message != null) {
87 Preconditions.checkArgument(xid.equals(message.getXid()), "Message %s has wrong XID %s, expected %s", message, message.getXid(), xid);
90 final int ro = reserveOffset;
91 Preconditions.checkArgument(offset < ro, "Unexpected commit to offset %s reserved %s message %s", offset, ro, message);
93 final OutboundQueueEntry entry = queue[offset];
94 entry.commit(message, callback);
95 LOG.debug("Queue {} XID {} at offset {} (of {}) committed", this, xid, offset, ro);
97 if (entry.isBarrier()) {
100 final int prev = BARRIER_OFFSET_UPDATER.getAndSet(this, my);
102 LOG.debug("Queue {} recorded pending barrier offset {}", this, my);
106 // We have traveled back, recover
111 manager.ensureFlushing(this);
114 private Long reserveEntry(final boolean forBarrier) {
115 final int offset = CURRENT_OFFSET_UPDATER.getAndIncrement(this);
116 if (offset >= reserve) {
118 LOG.debug("Queue {} offset {}/{}, using emergency slot", this, offset, queue.length);
121 LOG.debug("Queue {} offset {}/{}, not allowing reservation", this, offset, queue.length);
126 final Long xid = baseXid + offset;
127 LOG.debug("Queue {} allocated XID {} at offset {}", this, xid, offset);
131 Long reserveBarrierIfNeeded() {
132 final int bo = barrierOffset;
133 if (bo >= flushOffset) {
134 LOG.debug("Barrier found at offset {} (currently at {})", bo, flushOffset);
137 return reserveEntry(true);
141 int startShutdown() {
142 // Increment the offset by the queue size, hence preventing any normal
143 // allocations. We should not be seeing a barrier reservation after this
144 // and if there is one issued, we can disregard it.
145 final int offset = CURRENT_OFFSET_UPDATER.getAndAdd(this, queue.length);
147 // If this offset is larger than reserve, trim it. That is not an accurate
148 // view of which slot was actually "reserved", but it indicates at which
149 // entry we can declare the queue flushed (e.g. at the emergency slot).
150 return offset > reserve ? reserve : offset;
153 boolean isShutdown(final int offset) {
154 // This queue is shutdown if the flushOffset (e.g. the next entry to
155 // be flushed) points to the offset 'reserved' in startShutdown()
156 return flushOffset >= offset;
160 * An empty queue is a queue which has no further unflushed entries.
162 * @return True if this queue does not have unprocessed entries.
164 private boolean isEmpty() {
165 int ro = reserveOffset;
167 if (queue[reserve].isCommitted()) {
174 LOG.debug("Effective flush/reserve offset {}/{}", flushOffset, ro);
175 return ro <= flushOffset;
179 * A queue is finished when all of its entries have been completed.
181 * @return False if there are any uncompleted requests.
183 boolean isFinished() {
184 if (completeCount < reserve) {
188 // We need to check if the last entry was used
189 final OutboundQueueEntry last = queue[reserve];
190 return !last.isCommitted() || last.isCompleted();
193 boolean isFlushed() {
194 LOG.debug("Check queue {} for completeness (offset {}, reserve {})", this, flushOffset, reserve);
195 if (flushOffset < reserve) {
199 // flushOffset implied == reserve
200 return flushOffset >= queue.length || !queue[reserve].isCommitted();
203 boolean needsFlush() {
204 if (flushOffset < reserve) {
205 return queue[flushOffset].isCommitted();
209 LOG.trace("Queue {} is flushed, schedule a replace", this);
213 LOG.trace("Queue {} is finished, schedule a cleanup", this);
220 OfHeader flushEntry() {
224 LOG.trace("Flushed all reserved entries up to {}", flushOffset);
228 final OutboundQueueEntry entry = queue[flushOffset];
229 if (!entry.isCommitted()) {
230 LOG.trace("Request at offset {} not ready yet, giving up", flushOffset);
234 final OfHeader msg = entry.getMessage();
240 LOG.trace("Null message, skipping to offset {}", flushOffset);
244 // Argument is 'long' to explicitly convert before performing operations
245 private boolean xidInRange(final long xid) {
246 return xid < endXid && (xid >= baseXid || baseXid > endXid);
249 private static boolean completeEntry(final OutboundQueueEntry entry, final OfHeader response) {
250 if (response instanceof Error) {
251 final Error err = (Error)response;
252 LOG.debug("Device-reported request XID {} failed {}:{}", response.getXid(), err.getTypeString(), err.getCodeString());
253 entry.fail(new DeviceRequestFailedException("Device-side failure", err));
256 return entry.complete(response);
261 * Return the request entry corresponding to a response. Returns null
262 * if there is no request matching the response.
264 * @param response Response message
265 * @return Matching request entry, or null if no match is found.
267 OutboundQueueEntry pairRequest(@Nonnull final OfHeader response) {
268 final Long xid = response.getXid();
269 if (!xidInRange(xid)) {
270 LOG.debug("Queue {} {}/{} ignoring XID {}", this, baseXid, queue.length, xid);
274 final int offset = (int)(xid - baseXid);
275 final OutboundQueueEntry entry = queue[offset];
276 if (entry.isCompleted()) {
277 LOG.debug("Entry {} already is completed, not accepting response {}", entry, response);
281 if (entry.isBarrier()) {
282 // This has been a barrier -- make sure we complete all preceding requests.
283 // XXX: Barriers are expected to complete in one message.
284 // If this assumption is changed, this logic will need to be expanded
285 // to ensure that the requests implied by the barrier are reported as
286 // completed *after* the barrier.
287 LOG.trace("Barrier XID {} completed, cascading completion to XIDs {} to {}", xid, baseXid + lastBarrierOffset + 1, xid - 1);
288 completeRequests(offset);
289 lastBarrierOffset = offset;
291 final boolean success = completeEntry(entry, response);
292 Verify.verify(success, "Barrier request failed to complete");
294 } else if (completeEntry(entry, response)) {
301 private void completeRequests(final int toOffset) {
302 for (int i = lastBarrierOffset + 1; i < toOffset; ++i) {
303 final OutboundQueueEntry entry = queue[i];
304 if (!entry.isCompleted() && entry.complete(null)) {
311 completeRequests(queue.length);
314 int failAll(final OutboundQueueException cause) {
316 for (int i = lastBarrierOffset + 1; i < queue.length; ++i) {
317 final OutboundQueueEntry entry = queue[i];
318 if (!entry.isCommitted()) {
322 if (!entry.isCompleted()) {