Bug 542 - Plugin internal stats
[openflowplugin.git] / openflowplugin / src / main / java / org / opendaylight / openflowplugin / openflow / md / queue / QueueProcessorLightImpl.java
1 /**
2  * Copyright (c) 2013 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.openflowplugin.openflow.md.queue;
9
10 import java.util.Collection;
11 import java.util.Comparator;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.concurrent.ArrayBlockingQueue;
15 import java.util.concurrent.BlockingQueue;
16 import java.util.concurrent.ConcurrentSkipListSet;
17 import java.util.concurrent.ExecutorService;
18 import java.util.concurrent.Future;
19 import java.util.concurrent.RejectedExecutionHandler;
20 import java.util.concurrent.ThreadPoolExecutor;
21 import java.util.concurrent.TimeUnit;
22
23 import org.opendaylight.openflowplugin.openflow.md.core.IMDMessageTranslator;
24 import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor;
25 import org.opendaylight.openflowplugin.openflow.md.core.TranslatorKey;
26 import org.opendaylight.openflowplugin.statistics.MessageSpy;
27 import org.opendaylight.openflowplugin.statistics.MessageSpy.STATISTIC_GROUP;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
29 import org.opendaylight.yangtools.yang.binding.DataContainer;
30 import org.opendaylight.yangtools.yang.binding.DataObject;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34
35 /**
36  * {@link QueueKeeper} implementation focused to keep order and use up mutiple threads for translation phase.
37  * <br/>
38  * There is internal thread pool of limited size ({@link QueueProcessorLightImpl#setProcessingPoolSize(int)}) 
39  * dedicated to translation. Then there is singleThreadPool dedicated to publishing (via popListeners)
40  * <br/>
41  * Workflow:
42  * <ol>
43  * <li>upon message push ticket is created and enqueued</li>
44  * <li>available threads from internal pool translate the massage wrapped in ticket</li>
45  * <li>when translation of particular message is finished, result is set in future result of wrapping ticket</br>
46  *     (order of tickets in queue is not touched during translate)
47  * </li>
48  * <li>at the end of queue there is {@link TicketFinisher} running in singleThreadPool and for each ticket it does:
49  *    <ol>
50  *      <li>invoke blocking {@link BlockingQueue#take()} method in order to get the oldest ticket</li>
51  *      <li>invoke blocking {@link Future#get()} on the dequeued ticket</li>
52  *      <li>as soon as the result of translation is available, appropriate popListener is invoked</li>
53  *    </ol>
54  *    and this way the order of messages is preserved and also multiple threads are used by translating 
55  * </li>
56  * </ol>
57  * 
58  * 
59  */
60 public class QueueProcessorLightImpl implements QueueProcessor<OfHeader, DataObject> {
61
62     protected static final Logger LOG = LoggerFactory
63             .getLogger(QueueProcessorLightImpl.class);
64
65     private BlockingQueue<TicketResult<DataObject>> ticketQueue;
66     private ThreadPoolExecutor processorPool;
67     private int processingPoolSize = 4;
68     private ExecutorService harvesterPool;
69     private ExecutorService finisherPool;
70     
71     protected Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> popListenersMapping;
72     private Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> translatorMapping;
73     private TicketProcessorFactory<OfHeader, DataObject> ticketProcessorFactory;
74     private MessageSpy<DataContainer> messageSpy;
75     protected Collection<QueueKeeper<OfHeader>> messageSources;
76     private QueueKeeperHarvester<OfHeader> harvester;
77
78     protected TicketFinisher<DataObject> finisher;
79
80     /**
81      * prepare queue
82      */
83     public void init() {
84         int ticketQueueCapacity = 1500;
85         ticketQueue = new ArrayBlockingQueue<>(ticketQueueCapacity);
86         messageSources = new ConcurrentSkipListSet<>(
87                 new Comparator<QueueKeeper<OfHeader>>() {
88                     @Override
89                     public int compare(QueueKeeper<OfHeader> o1,
90                             QueueKeeper<OfHeader> o2) {
91                         return Integer.valueOf(o1.hashCode()).compareTo(o2.hashCode());
92                     }
93                 });
94         
95         processorPool = new ThreadPoolLoggingExecutor(processingPoolSize, processingPoolSize, 0, 
96                 TimeUnit.MILLISECONDS, 
97                 new ArrayBlockingQueue<Runnable>(ticketQueueCapacity), 
98                 "OFmsgProcessor");
99         // force blocking when pool queue is full
100         processorPool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
101             @Override
102             public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
103                 try {
104                     executor.getQueue().put(r);
105                 } catch (InterruptedException e) {
106                     Thread.currentThread().interrupt();
107                     throw new IllegalStateException(e);
108                 }
109             }
110         });
111         
112         harvesterPool = new ThreadPoolLoggingExecutor(1, 1, 0, 
113                 TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), "OFmsgHarvester");
114         finisherPool = new ThreadPoolLoggingExecutor(1, 1, 0, 
115                 TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), "OFmsgFinisher");
116         finisher = new TicketFinisherImpl(
117                 ticketQueue, popListenersMapping);
118         finisherPool.execute(finisher);
119         
120         harvester = new QueueKeeperHarvester<OfHeader>(this, messageSources);
121         harvesterPool.execute(harvester);
122
123         ticketProcessorFactory = new TicketProcessorFactoryImpl();
124         ticketProcessorFactory.setTranslatorMapping(translatorMapping);
125         ticketProcessorFactory.setSpy(messageSpy);
126         ticketProcessorFactory.setTicketFinisher(finisher);
127     }
128
129     /**
130      * stop processing queue
131      */
132     public void shutdown() {
133         processorPool.shutdown();
134     }
135
136     @Override
137     public void enqueueQueueItem(QueueItem<OfHeader> queueItem) {
138         messageSpy.spyMessage(queueItem.getMessage(), STATISTIC_GROUP.FROM_SWITCH_ENQUEUED);
139         TicketImpl<OfHeader, DataObject> ticket = new TicketImpl<>();
140         ticket.setConductor(queueItem.getConnectionConductor());
141         ticket.setMessage(queueItem.getMessage());
142         ticket.setQueueType(queueItem.getQueueType());
143         
144         LOG.trace("ticket scheduling: {}, ticket: {}",
145                 queueItem.getMessage().getImplementedInterface().getSimpleName(), 
146                 System.identityHashCode(queueItem));
147         scheduleTicket(ticket);
148     }
149     
150     
151     @Override
152     public void directProcessQueueItem(QueueItem<OfHeader> queueItem) {
153         messageSpy.spyMessage(queueItem.getMessage(), STATISTIC_GROUP.FROM_SWITCH_ENQUEUED);
154         TicketImpl<OfHeader, DataObject> ticket = new TicketImpl<>();
155         ticket.setConductor(queueItem.getConnectionConductor());
156         ticket.setMessage(queueItem.getMessage());
157         
158         LOG.debug("ticket scheduling: {}, ticket: {}",
159                 queueItem.getMessage().getImplementedInterface().getSimpleName(), 
160                 System.identityHashCode(queueItem));
161         
162         ticketProcessorFactory.createProcessor(ticket).run();
163         
164         // publish notification
165         finisher.firePopNotification(ticket.getDirectResult());
166     }
167
168     /**
169      * @param ticket
170      */
171     private void scheduleTicket(Ticket<OfHeader, DataObject> ticket) {
172         switch (ticket.getQueueType()) {
173         case DEFAULT:
174             Runnable ticketProcessor = ticketProcessorFactory.createProcessor(ticket);
175             processorPool.execute(ticketProcessor);
176             try {
177                 ticketQueue.put(ticket);
178             } catch (InterruptedException e) {
179                 LOG.warn("enqeueue of unordered message ticket failed", e);
180             }
181             break;
182         case UNORDERED:
183             Runnable ticketProcessorSync = ticketProcessorFactory.createSyncProcessor(ticket);
184             processorPool.execute(ticketProcessorSync);
185             break;
186         default:
187             LOG.warn("unsupported enqueue type: {}", ticket.getQueueType());
188         }
189     }
190
191     /**
192      * @param poolSize the poolSize to set
193      */
194     public void setProcessingPoolSize(int poolSize) {
195         this.processingPoolSize = poolSize;
196     }
197
198     @Override
199     public void setTranslatorMapping(
200             Map<TranslatorKey, Collection<IMDMessageTranslator<OfHeader, List<DataObject>>>> translatorMapping) {
201         this.translatorMapping = translatorMapping;
202     }
203
204     @Override
205     public void setPopListenersMapping(
206             Map<Class<? extends DataObject>, Collection<PopListener<DataObject>>> popListenersMapping) {
207         this.popListenersMapping = popListenersMapping;
208     }
209
210     /**
211      * @param messageSpy the messageSpy to set
212      */
213     public void setMessageSpy(MessageSpy<DataContainer> messageSpy) {
214         this.messageSpy = messageSpy;
215     }
216
217     @Override
218     public AutoCloseable registerMessageSource(QueueKeeper<OfHeader> queue) {
219         boolean added = messageSources.add(queue);
220         if (! added) {
221             LOG.debug("registration of message source queue failed - already registered");
222         }
223         MessageSourcePollRegistration<QueueKeeper<OfHeader>> queuePollRegistration = 
224                 new MessageSourcePollRegistration<>(this, queue);
225         return queuePollRegistration;
226     }
227     
228     @Override
229     public boolean unregisterMessageSource(QueueKeeper<OfHeader> queue) {
230         return messageSources.remove(queue);
231     }
232     
233     @Override
234     public Collection<QueueKeeper<OfHeader>> getMessageSources() {
235         return messageSources;
236     }
237     
238     @Override
239     public HarvesterHandle getHarvesterHandle() {
240         return harvester;
241     }
242 }