c9c28c16769cdbf4a498bf92f37de0e1ea447971
[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 int ro = reserveOffset;
91         Preconditions.checkArgument(offset < ro, "Unexpected commit to offset %s reserved %s message %s", offset, ro, message);
92
93         final OutboundQueueEntry entry = queue[offset];
94         entry.commit(message, callback);
95         LOG.debug("Queue {} XID {} at offset {} (of {}) committed", this, xid, offset, ro);
96
97         if (entry.isBarrier()) {
98             int my = offset;
99             for (;;) {
100                 final int prev = BARRIER_OFFSET_UPDATER.getAndSet(this, my);
101                 if (prev < my) {
102                     LOG.debug("Queue {} recorded pending barrier offset {}", this, my);
103                     break;
104                 }
105
106                 // We have traveled back, recover
107                 my = prev;
108             }
109         }
110
111         manager.ensureFlushing(this);
112     }
113
114     private Long reserveEntry(final boolean forBarrier) {
115         final int offset = CURRENT_OFFSET_UPDATER.getAndIncrement(this);
116         if (offset >= reserve) {
117             if (forBarrier) {
118                 LOG.debug("Queue {} offset {}/{}, using emergency slot", this, offset, queue.length);
119                 return endXid;
120             } else {
121                 LOG.debug("Queue {} offset {}/{}, not allowing reservation", this, offset, queue.length);
122                 return null;
123             }
124         }
125
126         final Long xid = baseXid + offset;
127         LOG.debug("Queue {} allocated XID {} at offset {}", this, xid, offset);
128         return xid;
129     }
130
131     Long reserveBarrierIfNeeded() {
132         final int bo = barrierOffset;
133         if (bo >= flushOffset) {
134             LOG.debug("Barrier found at offset {} (currently at {})", bo, flushOffset);
135             return null;
136         } else {
137             return reserveEntry(true);
138         }
139     }
140
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);
146
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;
151     }
152
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;
157     }
158
159     /**
160      * An empty queue is a queue which has no further unflushed entries.
161      *
162      * @return True if this queue does not have unprocessed entries.
163      */
164     private boolean isEmpty() {
165         int ro = reserveOffset;
166         if (ro >= reserve) {
167             if (queue[reserve].isCommitted()) {
168                 ro = reserve + 1;
169             } else {
170                 ro = reserve;
171             }
172         }
173
174         LOG.debug("Effective flush/reserve offset {}/{}", flushOffset, ro);
175         return ro <= flushOffset;
176     }
177
178     /**
179      * A queue is finished when all of its entries have been completed.
180      *
181      * @return False if there are any uncompleted requests.
182      */
183     boolean isFinished() {
184         if (completeCount < reserve) {
185             return false;
186         }
187
188         // We need to check if the last entry was used
189         final OutboundQueueEntry last = queue[reserve];
190         return !last.isCommitted() || last.isCompleted();
191     }
192
193     boolean isFlushed() {
194         LOG.debug("Check queue {} for completeness (offset {}, reserve {})", this, flushOffset, reserve);
195         if (flushOffset < reserve) {
196             return false;
197         }
198
199         // flushOffset implied == reserve
200         return flushOffset >= queue.length || !queue[reserve].isCommitted();
201     }
202
203     boolean needsFlush() {
204         if (flushOffset < reserve) {
205             return queue[flushOffset].isCommitted();
206         }
207
208         if (isFlushed()) {
209             LOG.trace("Queue {} is flushed, schedule a replace", this);
210             return true;
211         }
212         if (isFinished()) {
213             LOG.trace("Queue {} is finished, schedule a cleanup", this);
214             return true;
215         }
216
217         return false;
218     }
219
220     OfHeader flushEntry() {
221         for (;;) {
222             // No message ready
223             if (isEmpty()) {
224                 LOG.trace("Flushed all reserved entries up to {}", flushOffset);
225                 return null;
226             }
227
228             final OutboundQueueEntry entry = queue[flushOffset];
229             if (!entry.isCommitted()) {
230                 LOG.trace("Request at offset {} not ready yet, giving up", flushOffset);
231                 return null;
232             }
233
234             final OfHeader msg = entry.getMessage();
235             flushOffset++;
236             if (msg != null) {
237                 return msg;
238             }
239
240             LOG.trace("Null message, skipping to offset {}", flushOffset);
241         }
242     }
243
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);
247     }
248
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));
254             return true;
255         } else {
256             return entry.complete(response);
257         }
258     }
259
260     /**
261      * Return the request entry corresponding to a response. Returns null
262      * if there is no request matching the response.
263      *
264      * @param response Response message
265      * @return Matching request entry, or null if no match is found.
266      */
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);
271             return null;
272         }
273
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);
278             return null;
279         }
280
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;
290
291             final boolean success = completeEntry(entry, response);
292             Verify.verify(success, "Barrier request failed to complete");
293             completeCount++;
294         } else if (completeEntry(entry, response)) {
295             completeCount++;
296         }
297
298         return entry;
299     }
300
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)) {
305                 completeCount++;
306             }
307         }
308     }
309
310     void completeAll() {
311         completeRequests(queue.length);
312     }
313
314     int failAll(final OutboundQueueException cause) {
315         int ret = 0;
316         for (int i = lastBarrierOffset + 1; i < queue.length; ++i) {
317             final OutboundQueueEntry entry = queue[i];
318             if (!entry.isCommitted()) {
319                 break;
320             }
321
322             if (!entry.isCompleted()) {
323                 entry.fail(cause);
324                 ret++;
325             }
326         }
327
328         return ret;
329     }
330 }