BUG-3219: Fix debug arguments
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / core / connection / OutboundQueueImpl.java
1 /*
2  * Copyright (c) 2015 Pantheon Technologies s.r.o. 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.openflowjava.protocol.impl.core.connection;
9
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;
22
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;
34
35     // Updated concurrently
36     private volatile int barrierOffset = -1;
37     private volatile int reserveOffset = 0;
38
39     // Updated from Netty only
40     private int flushOffset;
41     private int completeCount;
42     private int lastBarrierOffset = -1;
43
44     OutboundQueueImpl(final OutboundQueueManager<?> manager, final long baseXid, final int maxQueue) {
45         /*
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.
51          */
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();
60         }
61     }
62
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) {
70             element.reset();
71         }
72     }
73
74     OutboundQueueImpl reuse(final long baseXid) {
75         return new OutboundQueueImpl(manager, baseXid, queue);
76     }
77
78     @Override
79     public Long reserveEntry() {
80         return reserveEntry(false);
81     }
82
83     @Override
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);
88         }
89
90         final OutboundQueueEntry entry = queue[offset];
91         entry.commit(message, callback);
92         LOG.debug("Queue {} XID {} at offset {} (of {}) committed", this, xid, offset, reserveOffset);
93
94         if (entry.isBarrier()) {
95             int my = offset;
96             for (;;) {
97                 final int prev = BARRIER_OFFSET_UPDATER.getAndSet(this, my);
98                 if (prev < my) {
99                     LOG.debug("Queue {} recorded pending barrier offset {}", this, my);
100                     break;
101                 }
102
103                 // We have traveled back, recover
104                 my = prev;
105             }
106         }
107
108         manager.ensureFlushing(this);
109     }
110
111     private Long reserveEntry(final boolean forBarrier) {
112         final int offset = CURRENT_OFFSET_UPDATER.getAndIncrement(this);
113         if (offset >= reserve) {
114             if (forBarrier) {
115                 LOG.debug("Queue {} offset {}/{}, using emergency slot", this, offset, queue.length);
116                 return endXid;
117             } else {
118                 LOG.debug("Queue {} offset {}/{}, not allowing reservation", this, offset, queue.length);
119                 return null;
120             }
121         }
122
123         final Long xid = baseXid + offset;
124         LOG.debug("Queue {} allocated XID {} at offset {}", this, xid, offset);
125         return xid;
126     }
127
128     Long reserveBarrierIfNeeded() {
129         final int bo = barrierOffset;
130         if (bo >= flushOffset) {
131             LOG.debug("Barrier found at offset {} (currently at {})", bo, flushOffset);
132             return null;
133         } else {
134             return reserveEntry(true);
135         }
136     }
137
138     int startShutdown() {
139         // Increment the offset by the queue size, hence preventing any normal
140         // allocations. We should not be seeing a barrier reservation after this
141         // and if there is one issued, we can disregard it.
142         final int offset = CURRENT_OFFSET_UPDATER.getAndAdd(this, queue.length);
143
144         // If this offset is larger than reserve, trim it. That is not an accurate
145         // view of which slot was actually "reserved", but it indicates at which
146         // entry we can declare the queue flushed (e.g. at the emergency slot).
147         return offset > reserve ? reserve : offset;
148     }
149
150     boolean isShutdown(final int offset) {
151         // This queue is shutdown if the flushOffset (e.g. the next entry to
152         // be flushed) points to the offset 'reserved' in startShutdown()
153         return flushOffset >= offset;
154     }
155
156     /**
157      * An empty queue is a queue which has no further unflushed entries.
158      *
159      * @return True if this queue does not have unprocessed entries.
160      */
161     private boolean isEmpty() {
162         int ro = reserveOffset;
163         if (ro >= reserve) {
164             if (queue[reserve].isCommitted()) {
165                 ro = reserve + 1;
166             } else {
167                 ro = reserve;
168             }
169         }
170
171         LOG.debug("Effective flush/reserve offset {}/{}", flushOffset, ro);
172         return ro <= flushOffset;
173     }
174
175     /**
176      * A queue is finished when all of its entries have been completed.
177      *
178      * @return False if there are any uncompleted requests.
179      */
180     boolean isFinished() {
181         if (completeCount < reserve) {
182             return false;
183         }
184
185         // We need to check if the last entry was used
186         final OutboundQueueEntry last = queue[reserve];
187         return !last.isCommitted() || last.isCompleted();
188     }
189
190     boolean isFlushed() {
191         LOG.debug("Check queue {} for completeness (offset {}, reserve {})", this, flushOffset, reserve);
192         if (flushOffset < reserve) {
193             return false;
194         }
195
196         // flushOffset implied == reserve
197         return flushOffset >= queue.length || !queue[reserve].isCommitted();
198     }
199
200     boolean needsFlush() {
201         if (flushOffset < reserve) {
202             return queue[flushOffset].isCommitted();
203         }
204
205         if (isFlushed()) {
206             LOG.trace("Queue {} is flushed, schedule a replace", this);
207             return true;
208         }
209         if (isFinished()) {
210             LOG.trace("Queue {} is finished, schedule a cleanup", this);
211             return true;
212         }
213
214         return false;
215     }
216
217     OfHeader flushEntry() {
218         for (;;) {
219             // No message ready
220             if (isEmpty()) {
221                 LOG.trace("Flushed all reserved entries up to ", flushOffset);
222                 return null;
223             }
224
225             final OutboundQueueEntry entry = queue[flushOffset];
226             if (!entry.isCommitted()) {
227                 LOG.trace("Request at offset {} not ready yet, giving up", flushOffset);
228                 return null;
229             }
230
231             final OfHeader msg = entry.getMessage();
232             flushOffset++;
233             if (msg != null) {
234                 return msg;
235             }
236
237             LOG.trace("Null message, skipping to offset {}", flushOffset);
238         }
239     }
240
241     // Argument is 'long' to explicitly convert before performing operations
242     private boolean xidInRange(final long xid) {
243         return xid < endXid && (xid >= baseXid || baseXid > endXid);
244     }
245
246     private static boolean completeEntry(final OutboundQueueEntry entry, final OfHeader response) {
247         if (response instanceof Error) {
248             final Error err = (Error)response;
249             LOG.debug("Device-reported request XID {} failed {}:{}", response.getXid(), err.getTypeString(), err.getCodeString());
250             entry.fail(new DeviceRequestFailedException("Device-side failure", err));
251             return true;
252         } else {
253             return entry.complete(response);
254         }
255     }
256
257     /**
258      * Return the request entry corresponding to a response. Returns null
259      * if there is no request matching the response.
260      *
261      * @param response Response message
262      * @return Matching request entry, or null if no match is found.
263      */
264     OutboundQueueEntry pairRequest(@Nonnull final OfHeader response) {
265         final Long xid = response.getXid();
266         if (!xidInRange(xid)) {
267             LOG.debug("Queue {} {}/{} ignoring XID {}", this, baseXid, queue.length, xid);
268             return null;
269         }
270
271         final int offset = (int)(xid - baseXid);
272         final OutboundQueueEntry entry = queue[offset];
273         if (entry.isCompleted()) {
274             LOG.debug("Entry {} already is completed, not accepting response {}", entry, response);
275             return null;
276         }
277
278         if (entry.isBarrier()) {
279             // This has been a barrier -- make sure we complete all preceding requests.
280             // XXX: Barriers are expected to complete in one message.
281             //      If this assumption is changed, this logic will need to be expanded
282             //      to ensure that the requests implied by the barrier are reported as
283             //      completed *after* the barrier.
284             LOG.trace("Barrier XID {} completed, cascading completion to XIDs {} to {}", xid, baseXid + lastBarrierOffset + 1, xid - 1);
285             completeRequests(offset);
286             lastBarrierOffset = offset;
287
288             final boolean success = completeEntry(entry, response);
289             Verify.verify(success, "Barrier request failed to complete");
290             completeCount++;
291         } else if (completeEntry(entry, response)) {
292             completeCount++;
293         }
294
295         return entry;
296     }
297
298     private void completeRequests(final int toOffset) {
299         for (int i = lastBarrierOffset + 1; i < toOffset; ++i) {
300             final OutboundQueueEntry entry = queue[i];
301             if (!entry.isCompleted() && entry.complete(null)) {
302                 completeCount++;
303             }
304         }
305     }
306
307     void completeAll() {
308         completeRequests(queue.length);
309     }
310
311     int failAll(final OutboundQueueException cause) {
312         int ret = 0;
313         for (int i = lastBarrierOffset + 1; i < queue.length; ++i) {
314             final OutboundQueueEntry entry = queue[i];
315             if (!entry.isCommitted()) {
316                 break;
317             }
318
319             if (!entry.isCompleted()) {
320                 entry.fail(cause);
321                 ret++;
322             }
323         }
324
325         return ret;
326     }
327 }