2 * Copyright (c) 2015 Cisco Systems, Inc. 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
9 package org.opendaylight.openflowjava.protocol.impl.core.connection;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Verify;
13 import com.google.common.util.concurrent.FutureCallback;
14 import io.netty.channel.Channel;
15 import java.util.ArrayList;
16 import java.util.Iterator;
17 import java.util.List;
18 import java.util.concurrent.atomic.AtomicLongFieldUpdater;
19 import org.checkerframework.checker.lock.qual.GuardedBy;
20 import org.checkerframework.checker.lock.qual.Holding;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
23 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueException;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
28 abstract class AbstractStackedOutboundQueue implements OutboundQueue {
30 private static final Logger LOG = LoggerFactory.getLogger(AbstractStackedOutboundQueue.class);
31 protected static final AtomicLongFieldUpdater<AbstractStackedOutboundQueue> LAST_XID_OFFSET_UPDATER =
32 AtomicLongFieldUpdater.newUpdater(AbstractStackedOutboundQueue.class, "lastXid");
34 @GuardedBy("unflushedSegments")
35 protected volatile StackedSegment firstSegment;
36 @GuardedBy("unflushedSegments")
37 protected final List<StackedSegment> unflushedSegments = new ArrayList<>(2);
38 @GuardedBy("unflushedSegments")
39 protected final List<StackedSegment> uncompletedSegments = new ArrayList<>(2);
41 private volatile long lastXid = -1;
42 private volatile long allocatedXid = -1;
44 @GuardedBy("unflushedSegments")
45 protected Integer shutdownOffset;
47 // Accessed from Netty only
48 protected int flushOffset;
50 protected final AbstractOutboundQueueManager<?, ?> manager;
52 AbstractStackedOutboundQueue(final AbstractOutboundQueueManager<?, ?> manager) {
53 this.manager = Preconditions.checkNotNull(manager);
54 firstSegment = StackedSegment.create(0L);
55 uncompletedSegments.add(firstSegment);
56 unflushedSegments.add(firstSegment);
60 public void commitEntry(final Long xid, final OfHeader message, final FutureCallback<OfHeader> callback) {
61 commitEntry(xid, message, callback, OutboundQueueEntry.DEFAULT_IS_COMPLETE);
64 @Holding("unflushedSegments")
65 protected void ensureSegment(final StackedSegment first, final int offset) {
66 final int segmentOffset = offset / StackedSegment.SEGMENT_SIZE;
67 LOG.debug("Queue {} slow offset {} maps to {} segments {}", this, offset, segmentOffset,
68 unflushedSegments.size());
70 for (int i = unflushedSegments.size(); i <= segmentOffset; ++i) {
71 final StackedSegment newSegment = StackedSegment.create(first.getBaseXid()
72 + StackedSegment.SEGMENT_SIZE * (long)i);
73 LOG.debug("Adding segment {}", newSegment);
74 unflushedSegments.add(newSegment);
77 allocatedXid = unflushedSegments.get(unflushedSegments.size() - 1).getEndXid();
81 * This method is expected to be called from multiple threads concurrently.
84 public Long reserveEntry() {
85 final long xid = LAST_XID_OFFSET_UPDATER.incrementAndGet(this);
86 final StackedSegment fastSegment = firstSegment;
88 if (xid >= fastSegment.getBaseXid() + StackedSegment.SEGMENT_SIZE) {
89 if (xid >= allocatedXid) {
90 // Multiple segments, this a slow path
91 LOG.debug("Queue {} falling back to slow reservation for XID {}", this, xid);
93 synchronized (unflushedSegments) {
94 LOG.debug("Queue {} executing slow reservation for XID {}", this, xid);
96 // Shutdown was scheduled, need to fail the reservation
97 if (shutdownOffset != null) {
98 LOG.debug("Queue {} is being shutdown, failing reservation", this);
102 // Ensure we have the appropriate segment for the specified XID
103 final StackedSegment slowSegment = firstSegment;
104 final int slowOffset = (int) (xid - slowSegment.getBaseXid());
105 Verify.verify(slowOffset >= 0);
107 // Now, we let's see if we need to allocate a new segment
108 ensureSegment(slowSegment, slowOffset);
110 LOG.debug("Queue {} slow reservation finished", this);
113 LOG.debug("Queue {} XID {} is already backed", this, xid);
117 LOG.trace("Queue {} allocated XID {}", this, xid);
122 * Write some entries from the queue to the channel. Guaranteed to run
123 * in the corresponding EventLoop.
125 * @param channel Channel onto which we are writing
126 * @param now time stamp
127 * @return Number of entries written out
129 int writeEntries(@NonNull final Channel channel, final long now) {
131 StackedSegment segment = firstSegment;
134 while (channel.isWritable()) {
135 final OutboundQueueEntry entry = segment.getEntry(flushOffset);
136 if (!entry.isCommitted()) {
137 LOG.debug("Queue {} XID {} segment {} offset {} not committed yet", this, segment.getBaseXid()
138 + flushOffset, segment, flushOffset);
142 LOG.trace("Queue {} flushing entry at offset {}", this, flushOffset);
143 final OfHeader message = entry.takeMessage();
147 if (message != null) {
148 manager.writeMessage(message, now);
150 entry.complete(null);
153 if (flushOffset >= StackedSegment.SEGMENT_SIZE) {
155 * Slow path: purge the current segment unless it's the last one.
156 * If it is, we leave it for replacement when a new reservation
159 * This costs us two slow paths, but hey, this should be very rare,
160 * so let's keep things simple.
162 synchronized (unflushedSegments) {
163 LOG.debug("Flush offset {} unflushed segments {}", flushOffset, unflushedSegments.size());
165 // We may have raced ahead of reservation code and need to allocate a segment
166 ensureSegment(segment, flushOffset);
168 // Remove the segment, update the firstSegment and reset flushOffset
169 final StackedSegment oldSegment = unflushedSegments.remove(0);
170 if (oldSegment.isComplete()) {
171 uncompletedSegments.remove(oldSegment);
172 oldSegment.recycle();
175 // Reset the first segment and add it to the uncompleted list
176 segment = unflushedSegments.get(0);
177 uncompletedSegments.add(segment);
179 // Update the shutdown offset
180 if (shutdownOffset != null) {
181 shutdownOffset -= StackedSegment.SEGMENT_SIZE;
184 // Allow reservations back on the fast path by publishing the new first segment
185 firstSegment = segment;
188 LOG.debug("Queue {} flush moved to segment {}", this, segment);
196 boolean pairRequest(final OfHeader message) {
197 Iterator<StackedSegment> it = uncompletedSegments.iterator();
198 while (it.hasNext()) {
199 final StackedSegment queue = it.next();
200 final OutboundQueueEntry entry = queue.pairRequest(message);
205 LOG.trace("Queue {} accepted response {}", queue, message);
207 // This has been a barrier request, we need to flush all
209 if (entry.isBarrier() && uncompletedSegments.size() > 1) {
210 LOG.trace("Queue {} indicated request was a barrier", queue);
212 it = uncompletedSegments.iterator();
213 while (it.hasNext()) {
214 final StackedSegment q = it.next();
216 // We want to complete all queues before the current one, we will
217 // complete the current queue below
218 if (!queue.equals(q)) {
219 LOG.trace("Queue {} is implied finished", q);
229 if (queue.isComplete()) {
230 LOG.trace("Queue {} is finished", queue);
238 LOG.debug("Failed to find completion for message {}", message);
242 boolean needsFlush() {
243 // flushOffset always points to the first entry, which can be changed only
244 // from Netty, so we are fine here.
245 if (firstSegment.getBaseXid() + flushOffset > lastXid) {
249 if (shutdownOffset != null && flushOffset >= shutdownOffset) {
253 return firstSegment.getEntry(flushOffset).isCommitted();
256 long startShutdown() {
258 * We are dealing with a multi-threaded shutdown, as the user may still
259 * be reserving entries in the queue. We are executing in a netty thread,
260 * so neither flush nor barrier can be running, which is good news.
261 * We will eat up all the slots in the queue here and mark the offset first
262 * reserved offset and free up all the cached queues. We then schedule
263 * the flush task, which will deal with the rest of the shutdown process.
265 synchronized (unflushedSegments) {
266 // Increment the offset by the segment size, preventing fast path allocations,
267 // since we are holding the slow path lock, any reservations will see the queue
268 // in shutdown and fail accordingly.
269 final long xid = LAST_XID_OFFSET_UPDATER.addAndGet(this, StackedSegment.SEGMENT_SIZE);
270 shutdownOffset = (int) (xid - firstSegment.getBaseXid() - StackedSegment.SEGMENT_SIZE);
272 // Fails all uncompleted entries, because they will never be completed due to disconnected channel.
273 return lockedFailSegments(uncompletedSegments.iterator());
278 * Checks if the shutdown is in final phase -> all allowed entries (number of entries < shutdownOffset) are flushed
279 * and fails all not completed entries (if in final phase).
281 * @param channel netty channel
282 * @return true if in final phase, false if a flush is needed
284 boolean finishShutdown(final Channel channel) {
286 synchronized (unflushedSegments) {
287 // Fails all entries, that were flushed in shutdownOffset (became uncompleted)
288 // - they will never be completed due to disconnected channel.
289 lockedFailSegments(uncompletedSegments.iterator());
290 // If no further flush is needed or we are not able to write to channel anymore, then we fail all unflushed
291 // segments, so that each enqueued entry is reported as unsuccessful due to channel disconnection.
292 // No further entries should be enqueued by this time.
293 needsFlush = channel.isWritable() && needsFlush();
295 lockedFailSegments(unflushedSegments.iterator());
301 protected OutboundQueueEntry getEntry(final Long xid) {
302 final StackedSegment fastSegment = firstSegment;
303 final long calcOffset = xid - fastSegment.getBaseXid();
304 Preconditions.checkArgument(calcOffset >= 0, "Commit of XID %s does not match up with base XID %s",
305 xid, fastSegment.getBaseXid());
307 Verify.verify(calcOffset <= Integer.MAX_VALUE);
308 final int fastOffset = (int) calcOffset;
310 if (fastOffset >= StackedSegment.SEGMENT_SIZE) {
311 LOG.debug("Queue {} falling back to slow commit of XID {} at offset {}", this, xid, fastOffset);
313 final StackedSegment segment;
314 final int slowOffset;
315 synchronized (unflushedSegments) {
316 final StackedSegment slowSegment = firstSegment;
317 final long slowCalcOffset = xid - slowSegment.getBaseXid();
318 Verify.verify(slowCalcOffset >= 0 && slowCalcOffset <= Integer.MAX_VALUE);
319 slowOffset = (int) slowCalcOffset;
321 LOG.debug("Queue {} recalculated offset of XID {} to {}", this, xid, slowOffset);
322 segment = unflushedSegments.get(slowOffset / StackedSegment.SEGMENT_SIZE);
325 final int segOffset = slowOffset % StackedSegment.SEGMENT_SIZE;
326 LOG.debug("Queue {} slow commit of XID {} completed at offset {} (segment {} offset {})", this,
327 xid, slowOffset, segment, segOffset);
328 return segment.getEntry(segOffset);
330 return fastSegment.getEntry(fastOffset);
334 * Fails not completed entries in segments and frees completed segments.
336 * @param iterator list of segments to be failed
337 * @return number of failed entries
339 @GuardedBy("unflushedSegments")
340 private long lockedFailSegments(Iterator<StackedSegment> iterator) {
344 while (iterator.hasNext()) {
345 final StackedSegment segment = iterator.next();
347 entries += segment.failAll(OutboundQueueException.DEVICE_DISCONNECTED);
348 if (segment.isComplete()) {
349 LOG.trace("Cleared segment {}", segment);