Bug fix: flow statistics are not notified if empty
[controller.git] / opendaylight / protocol_plugins / openflow / src / main / java / org / opendaylight / controller / protocol_plugin / openflow / internal / OFStatisticsManager.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
9 package org.opendaylight.controller.protocol_plugin.openflow.internal;
10
11 import java.nio.ByteBuffer;
12 import java.util.ArrayList;
13 import java.util.Collections;
14 import java.util.Deque;
15 import java.util.HashMap;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Map.Entry;
19 import java.util.Set;
20 import java.util.Timer;
21 import java.util.TimerTask;
22 import java.util.concurrent.BlockingQueue;
23 import java.util.concurrent.ConcurrentHashMap;
24 import java.util.concurrent.ConcurrentMap;
25 import java.util.concurrent.CopyOnWriteArraySet;
26 import java.util.concurrent.LinkedBlockingDeque;
27 import java.util.concurrent.LinkedBlockingQueue;
28
29 import org.eclipse.osgi.framework.console.CommandInterpreter;
30 import org.eclipse.osgi.framework.console.CommandProvider;
31 import org.opendaylight.controller.protocol_plugin.openflow.IInventoryShimExternalListener;
32 import org.opendaylight.controller.protocol_plugin.openflow.IOFStatisticsListener;
33 import org.opendaylight.controller.protocol_plugin.openflow.IOFStatisticsManager;
34 import org.opendaylight.controller.protocol_plugin.openflow.core.IController;
35 import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch;
36 import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6Match;
37 import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6StatsReply;
38 import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6StatsRequest;
39 import org.opendaylight.controller.sal.core.Node;
40 import org.opendaylight.controller.sal.core.NodeConnector;
41 import org.opendaylight.controller.sal.core.Property;
42 import org.opendaylight.controller.sal.core.UpdateType;
43 import org.opendaylight.controller.sal.utils.HexEncode;
44 import org.openflow.protocol.OFError;
45 import org.openflow.protocol.OFMatch;
46 import org.openflow.protocol.OFPort;
47 import org.openflow.protocol.OFStatisticsRequest;
48 import org.openflow.protocol.statistics.OFAggregateStatisticsRequest;
49 import org.openflow.protocol.statistics.OFFlowStatisticsReply;
50 import org.openflow.protocol.statistics.OFFlowStatisticsRequest;
51 import org.openflow.protocol.statistics.OFPortStatisticsReply;
52 import org.openflow.protocol.statistics.OFPortStatisticsRequest;
53 import org.openflow.protocol.statistics.OFQueueStatisticsRequest;
54 import org.openflow.protocol.statistics.OFStatistics;
55 import org.openflow.protocol.statistics.OFStatisticsType;
56 import org.openflow.protocol.statistics.OFTableStatistics;
57 import org.openflow.protocol.statistics.OFVendorStatistics;
58 import org.openflow.util.HexString;
59 import org.osgi.framework.BundleContext;
60 import org.osgi.framework.FrameworkUtil;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 /**
65  * It periodically polls the different OF statistics from the OF switches and
66  * caches them for quick retrieval for the above layers' modules It also
67  * provides an API to directly query the switch about the statistics
68  */
69 public class OFStatisticsManager implements IOFStatisticsManager,
70 IInventoryShimExternalListener, CommandProvider {
71     private static final Logger log = LoggerFactory.getLogger(OFStatisticsManager.class);
72     private static final int INITIAL_SIZE = 64;
73     private static final long FLOW_STATS_PERIOD = 10000;
74     private static final long DESC_STATS_PERIOD = 60000;
75     private static final long PORT_STATS_PERIOD = 5000;
76     private static final long TABLE_STATS_PERIOD = 10000;
77     private static final long TICK = 1000;
78     private static short statisticsTickNumber = (short) (FLOW_STATS_PERIOD / TICK);
79     private static short descriptionTickNumber = (short) (DESC_STATS_PERIOD / TICK);
80     private static short portTickNumber = (short) (PORT_STATS_PERIOD / TICK);
81     private static short tableTickNumber = (short) (TABLE_STATS_PERIOD / TICK);
82     private static short factoredSamples = (short) 2;
83     private static short counter = 1;
84     private IController controller = null;
85     private ConcurrentMap<Long, List<OFStatistics>> flowStatistics;
86     private ConcurrentMap<Long, List<OFStatistics>> descStatistics;
87     private ConcurrentMap<Long, List<OFStatistics>> portStatistics;
88     private ConcurrentMap<Long, List<OFStatistics>> tableStatistics;
89     private List<OFStatistics> dummyList;
90     private ConcurrentMap<Long, StatisticsTicks> statisticsTimerTicks;
91     protected BlockingQueue<StatsRequest> pendingStatsRequests;
92     protected BlockingQueue<Long> switchPortStatsUpdated;
93     private Thread statisticsCollector;
94     private Thread txRatesUpdater;
95     private Timer statisticsTimer;
96     private TimerTask statisticsTimerTask;
97     private ConcurrentMap<Long, Boolean> switchSupportsVendorExtStats;
98     // Per port sampled (every portStatsPeriod) transmit rate
99     private Map<Long, Map<Short, TxRates>> txRates;
100     private Set<IOFStatisticsListener> statisticsListeners;
101
102     /**
103      * The object containing the latest factoredSamples tx rate samples for a
104      * given switch port
105      */
106     protected class TxRates {
107         // contains the latest factoredSamples sampled transmitted bytes
108         Deque<Long> sampledTxBytes;
109
110         public TxRates() {
111             sampledTxBytes = new LinkedBlockingDeque<Long>();
112         }
113
114         public void update(Long txBytes) {
115             /*
116              * Based on how many samples our average works on, we might have to
117              * remove the oldest sample
118              */
119             if (sampledTxBytes.size() == factoredSamples) {
120                 sampledTxBytes.removeLast();
121             }
122
123             // Add the latest sample to the top of the queue
124             sampledTxBytes.addFirst(txBytes);
125         }
126
127         /**
128          * Returns the average transmit rate in bps
129          *
130          * @return the average transmit rate [bps]
131          */
132         public long getAverageTxRate() {
133             long average = 0;
134             /*
135              * If we cannot provide the value for the time window length set
136              */
137             if (sampledTxBytes.size() < factoredSamples) {
138                 return average;
139             }
140             long increment = sampledTxBytes.getFirst() - sampledTxBytes
141                     .getLast();
142             long timePeriod = factoredSamples * PORT_STATS_PERIOD / TICK;
143             average = (8L * increment) / timePeriod;
144             return average;
145         }
146     }
147
148     public void setController(IController core) {
149         this.controller = core;
150     }
151
152     public void unsetController(IController core) {
153         if (this.controller == core) {
154             this.controller = null;
155         }
156     }
157
158     /**
159      * Function called by the dependency manager when all the required
160      * dependencies are satisfied
161      *
162      */
163     void init() {
164         flowStatistics = new ConcurrentHashMap<Long, List<OFStatistics>>();
165         descStatistics = new ConcurrentHashMap<Long, List<OFStatistics>>();
166         portStatistics = new ConcurrentHashMap<Long, List<OFStatistics>>();
167         tableStatistics = new ConcurrentHashMap<Long, List<OFStatistics>>();
168         dummyList = new ArrayList<OFStatistics>(1);
169         statisticsTimerTicks = new ConcurrentHashMap<Long, StatisticsTicks>(INITIAL_SIZE);
170         pendingStatsRequests = new LinkedBlockingQueue<StatsRequest>(INITIAL_SIZE);
171         switchPortStatsUpdated = new LinkedBlockingQueue<Long>(INITIAL_SIZE);
172         switchSupportsVendorExtStats = new ConcurrentHashMap<Long, Boolean>(INITIAL_SIZE);
173         txRates = new HashMap<Long, Map<Short, TxRates>>(INITIAL_SIZE);
174         statisticsListeners = new CopyOnWriteArraySet<IOFStatisticsListener>();
175
176         configStatsPollIntervals();
177
178         // Initialize managed timers
179         statisticsTimer = new Timer();
180         statisticsTimerTask = new TimerTask() {
181             @Override
182             public void run() {
183                 decrementTicks();
184             }
185         };
186
187         // Initialize Statistics collector thread
188         statisticsCollector = new Thread(new Runnable() {
189             @Override
190             public void run() {
191                 while (true) {
192                     try {
193                         StatsRequest req = pendingStatsRequests.take();
194                         queryStatisticsInternal(req.switchId, req.type);
195                     } catch (InterruptedException e) {
196                         log.warn("Flow Statistics Collector thread "
197                                 + "interrupted", e);
198                     }
199                 }
200             }
201         }, "Statistics Collector");
202
203         // Initialize Tx Rate Updater thread
204         txRatesUpdater = new Thread(new Runnable() {
205             @Override
206             public void run() {
207                 while (true) {
208                     try {
209                         long switchId = switchPortStatsUpdated.take();
210                         updatePortsTxRate(switchId);
211                     } catch (InterruptedException e) {
212                         log.warn("TX Rate Updater thread interrupted", e);
213                     }
214                 }
215             }
216         }, "TX Rate Updater");
217     }
218
219     /**
220      * Function called by the dependency manager when at least one dependency
221      * become unsatisfied or when the component is shutting down because for
222      * example bundle is being stopped.
223      *
224      */
225     void destroy() {
226     }
227
228     /**
229      * Function called by dependency manager after "init ()" is called and after
230      * the services provided by the class are registered in the service registry
231      *
232      */
233     void start() {
234         // Start managed timers
235         statisticsTimer.scheduleAtFixedRate(statisticsTimerTask, 0, TICK);
236
237         // Start statistics collector thread
238         statisticsCollector.start();
239
240         // Start bandwidth utilization computer thread
241         txRatesUpdater.start();
242
243         // OSGI console
244         registerWithOSGIConsole();
245     }
246
247     /**
248      * Function called by the dependency manager before the services exported by
249      * the component are unregistered, this will be followed by a "destroy ()"
250      * calls
251      *
252      */
253     void stop() {
254         // Stop managed timers
255         statisticsTimer.cancel();
256     }
257
258     public void setStatisticsListener(IOFStatisticsListener s) {
259         this.statisticsListeners.add(s);
260     }
261
262     public void unsetStatisticsListener(IOFStatisticsListener s) {
263         if (s != null) {
264             this.statisticsListeners.remove(s);
265         }
266     }
267
268     private void registerWithOSGIConsole() {
269         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
270         bundleContext.registerService(CommandProvider.class.getName(), this, null);
271     }
272
273     private static class StatsRequest {
274         protected Long switchId;
275         protected OFStatisticsType type;
276
277         public StatsRequest(Long d, OFStatisticsType t) {
278             switchId = d;
279             type = t;
280         }
281
282         @Override
283         public String toString() {
284             return "SReq = {switchId=" + switchId + ", type=" + type + "}";
285         }
286
287         @Override
288         public int hashCode() {
289             final int prime = 31;
290             int result = 1;
291             result = prime * result
292                     + ((switchId == null) ? 0 : switchId.hashCode());
293             result = prime * result + ((type == null) ? 0 : type.ordinal());
294             return result;
295         }
296
297         @Override
298         public boolean equals(Object obj) {
299             if (this == obj) {
300                 return true;
301             }
302             if (obj == null) {
303                 return false;
304             }
305             if (getClass() != obj.getClass()) {
306                 return false;
307             }
308             StatsRequest other = (StatsRequest) obj;
309             if (switchId == null) {
310                 if (other.switchId != null) {
311                     return false;
312                 }
313             } else if (!switchId.equals(other.switchId)) {
314                 return false;
315             }
316             if (type != other.type) {
317                 return false;
318             }
319             return true;
320         }
321     }
322
323     private void addStatisticsTicks(Long switchId) {
324         switchSupportsVendorExtStats.put(switchId, Boolean.TRUE); // Assume
325                                                                   // switch
326                                                                   // supports
327                                                                   // Vendor
328                                                                   // extension
329                                                                   // stats
330         statisticsTimerTicks.put(switchId, new StatisticsTicks(true));
331         log.debug("Added Switch {} to target pool",
332                 HexString.toHexString(switchId.longValue()));
333     }
334
335     protected static class StatisticsTicks {
336         private short flowStatisticsTicks;
337         private short descriptionTicks;
338         private short portStatisticsTicks;
339         private short tableStatisticsTicks;
340
341         public StatisticsTicks(boolean scattered) {
342             if (scattered) {
343                 // scatter bursts by statisticsTickPeriod
344                 if (++counter < 0) {
345                     counter = 0;
346                 } // being paranoid here
347                 flowStatisticsTicks = (short) (1 + counter
348                         % statisticsTickNumber);
349                 descriptionTicks = (short) (1 + counter % descriptionTickNumber);
350                 portStatisticsTicks = (short) (1 + counter % portTickNumber);
351                 tableStatisticsTicks = (short) (1 + counter % tableTickNumber);
352             } else {
353                 flowStatisticsTicks = statisticsTickNumber;
354                 descriptionTicks = descriptionTickNumber;
355                 portStatisticsTicks = portTickNumber;
356                 tableStatisticsTicks = tableTickNumber;
357             }
358         }
359
360         public boolean decrementFlowTicksIsZero() {
361             // Please ensure no code is inserted between the if check and the
362             // flowStatisticsTicks reset
363             if (--flowStatisticsTicks == 0) {
364                 flowStatisticsTicks = statisticsTickNumber;
365                 return true;
366             }
367             return false;
368         }
369
370         public boolean decrementDescTicksIsZero() {
371             // Please ensure no code is inserted between the if check and the
372             // descriptionTicks reset
373             if (--descriptionTicks == 0) {
374                 descriptionTicks = descriptionTickNumber;
375                 return true;
376             }
377             return false;
378         }
379
380         public boolean decrementPortTicksIsZero() {
381             // Please ensure no code is inserted between the if check and the
382             // descriptionTicks reset
383             if (--portStatisticsTicks == 0) {
384                 portStatisticsTicks = portTickNumber;
385                 return true;
386             }
387             return false;
388         }
389
390         public boolean decrementTableTicksIsZero() {
391             // Please ensure no code is inserted between the if check and the
392             // descriptionTicks reset
393             if(--tableStatisticsTicks == 0) {
394                 tableStatisticsTicks = tableTickNumber;
395                 return true;
396             }
397             return false;
398         }
399
400         @Override
401         public String toString() {
402             return "{fT=" + flowStatisticsTicks + ",dT=" + descriptionTicks
403                     + ",pT=" + portStatisticsTicks + ",tT=" + tableStatisticsTicks + "}";
404         }
405     }
406
407     private void printInfoMessage(String type, StatsRequest request) {
408         log.info("{} stats request not inserted for switch: {}. Queue size: {}. Collector state: {}.",
409                 new Object[] {type, HexString.toHexString(request.switchId), pendingStatsRequests.size(),
410                 statisticsCollector.getState().toString() });
411     }
412
413     protected void decrementTicks() {
414         StatsRequest request = null;
415         for (Map.Entry<Long, StatisticsTicks> entry : statisticsTimerTicks
416                 .entrySet()) {
417             StatisticsTicks clock = entry.getValue();
418             Long switchId = entry.getKey();
419             if (clock.decrementFlowTicksIsZero()) {
420                 request = (switchSupportsVendorExtStats.get(switchId) == Boolean.TRUE) ?
421                         new StatsRequest(switchId, OFStatisticsType.VENDOR) :
422                         new StatsRequest(switchId, OFStatisticsType.FLOW);
423                 // If a request for this switch is already in the queue, skip to
424                 // add this new request
425                 if (!pendingStatsRequests.contains(request)
426                         && false == pendingStatsRequests.offer(request)) {
427                     printInfoMessage("Flow", request);
428                 }
429             }
430
431             if (clock.decrementDescTicksIsZero()) {
432                 request = new StatsRequest(switchId, OFStatisticsType.DESC);
433                 // If a request for this switch is already in the queue, skip to
434                 // add this new request
435                 if (!pendingStatsRequests.contains(request)
436                         && false == pendingStatsRequests.offer(request)) {
437                     printInfoMessage("Description", request);
438                 }
439             }
440
441             if (clock.decrementPortTicksIsZero()) {
442                 request = new StatsRequest(switchId, OFStatisticsType.PORT);
443                 // If a request for this switch is already in the queue, skip to
444                 // add this new request
445                 if (!pendingStatsRequests.contains(request)
446                         && false == pendingStatsRequests.offer(request)) {
447                     printInfoMessage("Port", request);
448                 }
449             }
450
451             if(clock.decrementTableTicksIsZero()) {
452                 request = new StatsRequest(switchId, OFStatisticsType.TABLE);
453                 // If a request for this switch is already in the queue, skip to
454                 // add this new request
455                 if (!pendingStatsRequests.contains(request)
456                         && false == pendingStatsRequests.offer(request)) {
457                     printInfoMessage("Table", request);
458                 }
459             }
460         }
461     }
462
463     private void removeStatsRequestTasks(Long switchId) {
464         log.debug("Cleaning Statistics database for switch {}",
465                 HexEncode.longToHexString(switchId));
466         // To be safe, let's attempt removal of both VENDOR and FLOW request. It
467         // does not hurt
468         pendingStatsRequests.remove(new StatsRequest(switchId,
469                 OFStatisticsType.VENDOR));
470         pendingStatsRequests.remove(new StatsRequest(switchId,
471                 OFStatisticsType.FLOW));
472         pendingStatsRequests.remove(new StatsRequest(switchId,
473                 OFStatisticsType.DESC));
474         pendingStatsRequests.remove(new StatsRequest(switchId,
475                 OFStatisticsType.PORT));
476         pendingStatsRequests.remove(new StatsRequest(switchId,
477                 OFStatisticsType.TABLE));
478         // Take care of the TX rate databases
479         switchPortStatsUpdated.remove(switchId);
480         txRates.remove(switchId);
481     }
482
483     private void clearFlowStatsAndTicks(Long switchId) {
484         statisticsTimerTicks.remove(switchId);
485         removeStatsRequestTasks(switchId);
486         flowStatistics.remove(switchId);
487         log.debug("Statistics removed for switch {}",
488                 HexString.toHexString(switchId));
489     }
490
491     private void queryStatisticsInternal(Long switchId, OFStatisticsType statType) {
492
493         // Query the switch on all matches
494         List<OFStatistics> values = this.fetchStatisticsFromSwitch(switchId, statType, null);
495
496         // If got a valid response update local cache and notify listeners
497         if (values != null && !values.isEmpty()) {
498             switch (statType) {
499                 case FLOW:
500                 case VENDOR:
501                     flowStatistics.put(switchId, values);
502                     notifyFlowUpdate(switchId, values);
503                     break;
504                 case DESC:
505                     // Overwrite cache
506                     descStatistics.put(switchId, values);
507                     // Notify who may be interested in a description change
508                     notifyDescriptionUpdate(switchId, values);
509                     break;
510                 case PORT:
511                     // Overwrite cache with new port statistics for this switch
512                     portStatistics.put(switchId, values);
513
514                     // Wake up the thread which maintains the TX byte counters for
515                     // each port
516                     switchPortStatsUpdated.offer(switchId);
517                     notifyPortUpdate(switchId, values);
518                     break;
519                 case TABLE:
520                     // Overwrite cache
521                     tableStatistics.put(switchId, values);
522                     notifyTableUpdate(switchId, values);
523                     break;
524                 default:
525             }
526         }
527     }
528
529     private void notifyDescriptionUpdate(Long switchId, List<OFStatistics> values) {
530         for (IOFStatisticsListener l : this.statisticsListeners) {
531             l.descriptionStatisticsRefreshed(switchId, values);
532         }
533     }
534
535     private void notifyFlowUpdate(Long switchId, List<OFStatistics> values) {
536         if (values.get(0) instanceof OFVendorStatistics) {
537             values = this.v6StatsListToOFStatsList(values);
538         }
539
540         for (IOFStatisticsListener l : this.statisticsListeners) {
541             l.flowStatisticsRefreshed(switchId, values);
542         }
543
544     }
545
546     private void notifyPortUpdate(Long switchId, List<OFStatistics> values) {
547         for (IOFStatisticsListener l : this.statisticsListeners) {
548             l.portStatisticsRefreshed(switchId, values);
549         }
550     }
551
552     private void notifyTableUpdate(Long switchId, List<OFStatistics> values) {
553         for (IOFStatisticsListener l : this.statisticsListeners) {
554             l.tableStatisticsRefreshed(switchId, values);
555         }
556     }
557
558     /*
559      * Generic function to get the statistics form an OF switch
560      */
561     @SuppressWarnings("unchecked")
562     private List<OFStatistics> fetchStatisticsFromSwitch(Long switchId,
563             OFStatisticsType statsType, Object target) {
564         List<OFStatistics> values = null;
565         String type = null;
566         ISwitch sw = controller.getSwitch(switchId);
567
568         if (sw != null) {
569             OFStatisticsRequest req = new OFStatisticsRequest();
570             req.setStatisticType(statsType);
571             int requestLength = req.getLengthU();
572
573             if (statsType == OFStatisticsType.FLOW) {
574                 OFMatch match = null;
575                 if (target == null) {
576                     // All flows request
577                     match = new OFMatch();
578                     match.setWildcards(0xffffffff);
579                 } else if (!(target instanceof OFMatch)) {
580                     // Malformed request
581                     log.warn("Invalid target type for Flow stats request: {}",
582                             target.getClass());
583                     return null;
584                 } else {
585                     // Specific flow request
586                     match = (OFMatch) target;
587                 }
588                 OFFlowStatisticsRequest specificReq = new OFFlowStatisticsRequest();
589                 specificReq.setMatch(match);
590                 specificReq.setOutPort(OFPort.OFPP_NONE.getValue());
591                 specificReq.setTableId((byte) 0xff);
592                 req.setStatistics(Collections
593                         .singletonList((OFStatistics) specificReq));
594                 requestLength += specificReq.getLength();
595                 type = "FLOW";
596             } else if (statsType == OFStatisticsType.VENDOR) {
597                 V6StatsRequest specificReq = new V6StatsRequest();
598                 specificReq.setOutPort(OFPort.OFPP_NONE.getValue());
599                 specificReq.setTableId((byte) 0xff);
600                 req.setStatistics(Collections
601                         .singletonList((OFStatistics) specificReq));
602                 requestLength += specificReq.getLength();
603                 type = "VENDOR";
604             } else if (statsType == OFStatisticsType.AGGREGATE) {
605                 OFAggregateStatisticsRequest specificReq = new OFAggregateStatisticsRequest();
606                 OFMatch match = new OFMatch();
607                 match.setWildcards(0xffffffff);
608                 specificReq.setMatch(match);
609                 specificReq.setOutPort(OFPort.OFPP_NONE.getValue());
610                 specificReq.setTableId((byte) 0xff);
611                 req.setStatistics(Collections
612                         .singletonList((OFStatistics) specificReq));
613                 requestLength += specificReq.getLength();
614                 type = "AGGREGATE";
615             } else if (statsType == OFStatisticsType.PORT) {
616                 short targetPort;
617                 if (target == null) {
618                     // All ports request
619                     targetPort = OFPort.OFPP_NONE.getValue();
620                 } else if (!(target instanceof Short)) {
621                     // Malformed request
622                     log.warn("Invalid target type for Port stats request: {}",
623                             target.getClass());
624                     return null;
625                 } else {
626                     // Specific port request
627                     targetPort = (Short) target;
628                 }
629                 OFPortStatisticsRequest specificReq = new OFPortStatisticsRequest();
630                 specificReq.setPortNumber(targetPort);
631                 req.setStatistics(Collections
632                         .singletonList((OFStatistics) specificReq));
633                 requestLength += specificReq.getLength();
634                 type = "PORT";
635             } else if (statsType == OFStatisticsType.QUEUE) {
636                 OFQueueStatisticsRequest specificReq = new OFQueueStatisticsRequest();
637                 specificReq.setPortNumber(OFPort.OFPP_ALL.getValue());
638                 specificReq.setQueueId(0xffffffff);
639                 req.setStatistics(Collections
640                         .singletonList((OFStatistics) specificReq));
641                 requestLength += specificReq.getLength();
642                 type = "QUEUE";
643             } else if (statsType == OFStatisticsType.DESC) {
644                 type = "DESC";
645             } else if (statsType == OFStatisticsType.TABLE) {
646                 if(target != null){
647                     if (!(target instanceof Byte)) {
648                         // Malformed request
649                         log.warn("Invalid table id for table stats request: {}",
650                                 target.getClass());
651                         return null;
652                     }
653                     byte targetTable = (Byte) target;
654                     OFTableStatistics specificReq = new OFTableStatistics();
655                     specificReq.setTableId(targetTable);
656                     req.setStatistics(Collections
657                             .singletonList((OFStatistics) specificReq));
658                     requestLength += specificReq.getLength();
659                 }
660                 type = "TABLE";
661             }
662             req.setLengthU(requestLength);
663             Object result = sw.getStatistics(req);
664
665             if (result == null) {
666                 log.warn("Request Timed Out for ({}) from switch {}", type,
667                         HexString.toHexString(switchId));
668             } else if (result instanceof OFError) {
669                 log.warn("Switch {} failed to handle ({}) stats request: {}",
670                         new Object[] { HexString.toHexString(switchId), type,
671                         Utils.getOFErrorString((OFError) result) });
672                 if (this.switchSupportsVendorExtStats.get(switchId) == Boolean.TRUE) {
673                     log.warn(
674                             "Switching back to regular Flow stats requests for switch {}",
675                             HexString.toHexString(switchId));
676                     this.switchSupportsVendorExtStats.put(switchId,
677                             Boolean.FALSE);
678                 }
679             } else {
680                 values = (List<OFStatistics>) result;
681             }
682         }
683         return values;
684     }
685
686     @Override
687     public List<OFStatistics> getOFFlowStatistics(Long switchId) {
688         List<OFStatistics> list = flowStatistics.get(switchId);
689
690         /*
691          * Check on emptiness as interference between add and get is still
692          * possible on the inner list (the concurrentMap entry's value)
693          */
694         return (list == null || list.isEmpty()) ? this.dummyList
695                 : (list.get(0) instanceof OFVendorStatistics) ? this
696                         .v6StatsListToOFStatsList(list) : list;
697     }
698
699     @Override
700     public List<OFStatistics> getOFFlowStatistics(Long switchId, OFMatch ofMatch, short priority) {
701         List<OFStatistics> statsList = flowStatistics.get(switchId);
702
703         /*
704          * Check on emptiness as interference between add and get is still
705          * possible on the inner list (the concurrentMap entry's value)
706          */
707         if (statsList == null || statsList.isEmpty()) {
708             return this.dummyList;
709         }
710
711         if (statsList.get(0) instanceof OFVendorStatistics) {
712             /*
713              * Caller could provide regular OF match when we instead pull the
714              * vendor statistics from this node Caller is not supposed to know
715              * whether this switch supports vendor extensions statistics
716              * requests
717              */
718             V6Match targetMatch = (ofMatch instanceof V6Match) ? (V6Match) ofMatch
719                     : new V6Match(ofMatch);
720
721             List<OFStatistics> targetList = v6StatsListToOFStatsList(statsList);
722             for (OFStatistics stats : targetList) {
723                 V6StatsReply v6Stats = (V6StatsReply) stats;
724                 V6Match v6Match = v6Stats.getMatch();
725                 if (v6Stats.getPriority() == priority && v6Match.equals(targetMatch)) {
726                     List<OFStatistics> list = new ArrayList<OFStatistics>();
727                     list.add(stats);
728                     return list;
729                 }
730             }
731         } else {
732             for (OFStatistics stats : statsList) {
733                 OFFlowStatisticsReply flowStats = (OFFlowStatisticsReply) stats;
734                 if (flowStats.getPriority() == priority && flowStats.getMatch().equals(ofMatch)) {
735                     List<OFStatistics> list = new ArrayList<OFStatistics>();
736                     list.add(stats);
737                     return list;
738                 }
739             }
740         }
741         return this.dummyList;
742     }
743
744     /*
745      * Converts the v6 vendor statistics to the OFStatistics
746      */
747     private List<OFStatistics> v6StatsListToOFStatsList(
748             List<OFStatistics> statistics) {
749         List<OFStatistics> v6statistics = new ArrayList<OFStatistics>();
750         if (statistics != null && !statistics.isEmpty()) {
751             for (OFStatistics stats : statistics) {
752                 if (stats instanceof OFVendorStatistics) {
753                     List<OFStatistics> r = getV6ReplyStatistics((OFVendorStatistics) stats);
754                     if (r != null) {
755                         v6statistics.addAll(r);
756                     }
757                 }
758             }
759         }
760         return v6statistics;
761     }
762
763     private static List<OFStatistics> getV6ReplyStatistics(
764             OFVendorStatistics stat) {
765         int length = stat.getLength();
766         List<OFStatistics> results = new ArrayList<OFStatistics>();
767         if (length < 12)
768             return null; // Nicira Hdr is 12 bytes. We need atleast that much
769         ByteBuffer data = ByteBuffer.allocate(length);
770         stat.writeTo(data);
771         data.rewind();
772         if (log.isTraceEnabled()) {
773             log.trace("getV6ReplyStatistics: Buffer BYTES ARE {}",
774                     HexString.toHexString(data.array()));
775         }
776
777         int vendor = data.getInt(); // first 4 bytes is vendor id.
778         if (vendor != V6StatsRequest.NICIRA_VENDOR_ID) {
779             log.warn("Unexpected vendor id: 0x{}", Integer.toHexString(vendor));
780             return null;
781         } else {
782             // go ahead by 8 bytes which is 8 bytes of 0
783             data.getLong(); // should be all 0's
784             length -= 12; // 4 bytes Nicira Hdr + 8 bytes from above line have
785                           // been consumed
786         }
787
788         V6StatsReply v6statsreply;
789         int min_len;
790         while (length > 0) {
791             v6statsreply = new V6StatsReply();
792             min_len = v6statsreply.getLength();
793             if (length < v6statsreply.getLength())
794                 break;
795             v6statsreply.setActionFactory(stat.getActionFactory());
796             v6statsreply.readFrom(data);
797             if (v6statsreply.getLength() < min_len)
798                 break;
799             v6statsreply.setVendorId(vendor);
800             log.trace("V6StatsReply: {}", v6statsreply);
801             length -= v6statsreply.getLength();
802             results.add(v6statsreply);
803         }
804         return results;
805     }
806
807     @Override
808     public List<OFStatistics> queryStatistics(Long switchId,
809             OFStatisticsType statType, Object target) {
810         /*
811          * Caller does not know and it is not supposed to know whether this
812          * switch supports vendor extension. We adjust the target for him
813          */
814         if (statType == OFStatisticsType.FLOW) {
815             if (switchSupportsVendorExtStats.get(switchId) == Boolean.TRUE) {
816                 statType = OFStatisticsType.VENDOR;
817             }
818         }
819
820         List<OFStatistics> list = this.fetchStatisticsFromSwitch(switchId, statType,
821                 target);
822
823         return (list == null) ? null :
824             (statType == OFStatisticsType.VENDOR) ? v6StatsListToOFStatsList(list) : list;
825     }
826
827     @Override
828     public List<OFStatistics> getOFDescStatistics(Long switchId) {
829         if (!descStatistics.containsKey(switchId))
830             return this.dummyList;
831
832         return descStatistics.get(switchId);
833     }
834
835     @Override
836     public List<OFStatistics> getOFPortStatistics(Long switchId) {
837         if (!portStatistics.containsKey(switchId)) {
838             return this.dummyList;
839         }
840
841         return portStatistics.get(switchId);
842     }
843
844     @Override
845     public List<OFStatistics> getOFPortStatistics(Long switchId, short portId) {
846         if (!portStatistics.containsKey(switchId)) {
847             return this.dummyList;
848         }
849         List<OFStatistics> list = new ArrayList<OFStatistics>(1);
850         for (OFStatistics stats : portStatistics.get(switchId)) {
851             if (((OFPortStatisticsReply) stats).getPortNumber() == portId) {
852                 list.add(stats);
853                 break;
854             }
855         }
856         return list;
857     }
858
859     @Override
860     public List<OFStatistics> getOFTableStatistics(Long switchId) {
861         if (!tableStatistics.containsKey(switchId)) {
862             return this.dummyList;
863         }
864
865         return tableStatistics.get(switchId);
866     }
867
868     @Override
869     public List<OFStatistics> getOFTableStatistics(Long switchId, Byte tableId) {
870         if (!tableStatistics.containsKey(switchId)) {
871             return this.dummyList;
872         }
873
874         List<OFStatistics> list = new ArrayList<OFStatistics>(1);
875         for (OFStatistics stats : tableStatistics.get(switchId)) {
876             if (((OFTableStatistics) stats).getTableId() == tableId) {
877                 list.add(stats);
878                 break;
879             }
880         }
881         return list;
882     }
883
884     @Override
885     public int getFlowsNumber(long switchId) {
886         return this.flowStatistics.get(switchId).size();
887     }
888
889     /*
890      * InventoryShim replay for us all the switch addition which happened before
891      * we were brought up
892      */
893     @Override
894     public void updateNode(Node node, UpdateType type, Set<Property> props) {
895         Long switchId = (Long) node.getID();
896         switch (type) {
897         case ADDED:
898             addStatisticsTicks(switchId);
899             break;
900         case REMOVED:
901             clearFlowStatsAndTicks(switchId);
902         default:
903         }
904     }
905
906     @Override
907     public void updateNodeConnector(NodeConnector nodeConnector,
908             UpdateType type, Set<Property> props) {
909         // No action
910     }
911
912     /**
913      * Update the cached port rates for this switch with the latest retrieved
914      * port transmit byte count
915      *
916      * @param switchId
917      */
918     private synchronized void updatePortsTxRate(long switchId) {
919         List<OFStatistics> newPortStatistics = this.portStatistics.get(switchId);
920         if (newPortStatistics == null) {
921             return;
922         }
923         Map<Short, TxRates> rates = this.txRates.get(switchId);
924         if (rates == null) {
925             // First time rates for this switch are added
926             rates = new HashMap<Short, TxRates>();
927             txRates.put(switchId, rates);
928         }
929         for (OFStatistics stats : newPortStatistics) {
930             OFPortStatisticsReply newPortStat = (OFPortStatisticsReply) stats;
931             short port = newPortStat.getPortNumber();
932             TxRates portRatesHolder = rates.get(port);
933             if (portRatesHolder == null) {
934                 // First time rates for this port are added
935                 portRatesHolder = new TxRates();
936                 rates.put(port, portRatesHolder);
937             }
938             // Get and store the number of transmitted bytes for this port
939             // And handle the case where agent does not support the counter
940             long transmitBytes = newPortStat.getTransmitBytes();
941             long value = (transmitBytes < 0) ? 0 : transmitBytes;
942             portRatesHolder.update(value);
943         }
944     }
945
946     @Override
947     public synchronized long getTransmitRate(Long switchId, Short port) {
948         long average = 0;
949         if (switchId == null || port == null) {
950             return average;
951         }
952         Map<Short, TxRates> perSwitch = txRates.get(switchId);
953         if (perSwitch == null) {
954             return average;
955         }
956         TxRates portRates = perSwitch.get(port);
957         if (portRates == null) {
958             return average;
959         }
960         return portRates.getAverageTxRate();
961     }
962
963     /*
964      * Manual switch name configuration code
965      */
966     @Override
967     public String getHelp() {
968         StringBuffer help = new StringBuffer();
969         help.append("---OF Statistics Manager utilities---\n");
970         help.append("\t ofdumpstatsmgr         - "
971                 + "Print Internal Stats Mgr db\n");
972         help.append("\t ofstatsmgrintervals <fP> <pP> <dP> <tP> (all in seconds) - "
973                 + "Set/Show flow/port/dedscription stats poll intervals\n");
974         return help.toString();
975     }
976
977     private boolean isValidSwitchId(String switchId) {
978         String regexDatapathID = "^([0-9a-fA-F]{1,2}[:-]){7}[0-9a-fA-F]{1,2}$";
979         String regexDatapathIDLong = "^[0-9a-fA-F]{1,16}$";
980
981         return (switchId != null && (switchId.matches(regexDatapathID) || switchId
982                 .matches(regexDatapathIDLong)));
983     }
984
985     public long getSwitchIDLong(String switchId) {
986         int radix = 16;
987         String switchString = "0";
988
989         if (isValidSwitchId(switchId)) {
990             if (switchId.contains(":")) {
991                 // Handle the 00:00:AA:BB:CC:DD:EE:FF notation
992                 switchString = switchId.replace(":", "");
993             } else if (switchId.contains("-")) {
994                 // Handle the 00-00-AA-BB-CC-DD-EE-FF notation
995                 switchString = switchId.replace("-", "");
996             } else {
997                 // Handle the 0123456789ABCDEF notation
998                 switchString = switchId;
999             }
1000         }
1001         return Long.parseLong(switchString, radix);
1002     }
1003
1004     /*
1005      * Internal information dump code
1006      */
1007     private String prettyPrintSwitchMap(ConcurrentMap<Long, StatisticsTicks> map) {
1008         StringBuffer buffer = new StringBuffer();
1009         buffer.append("{");
1010         for (Entry<Long, StatisticsTicks> entry : map.entrySet()) {
1011             buffer.append(HexString.toHexString(entry.getKey()) + "="
1012                     + entry.getValue().toString() + " ");
1013         }
1014         buffer.append("}");
1015         return buffer.toString();
1016     }
1017
1018     public void _ofdumpstatsmgr(CommandInterpreter ci) {
1019         ci.println("Global Counter: " + counter);
1020         ci.println("Timer Ticks: " + prettyPrintSwitchMap(statisticsTimerTicks));
1021         ci.println("PendingStatsQueue: " + pendingStatsRequests);
1022         ci.println("PendingStatsQueue size: " + pendingStatsRequests.size());
1023         ci.println("Stats Collector alive: " + statisticsCollector.isAlive());
1024         ci.println("Stats Collector State: "
1025                 + statisticsCollector.getState().toString());
1026         ci.println("StatsTimer: " + statisticsTimer.toString());
1027         ci.println("Flow Stats Period: " + statisticsTickNumber + " s");
1028         ci.println("Desc Stats Period: " + descriptionTickNumber + " s");
1029         ci.println("Port Stats Period: " + portTickNumber + " s");
1030         ci.println("Table Stats Period: " + tableTickNumber + " s");
1031     }
1032
1033     public void _resetSwitchCapability(CommandInterpreter ci) {
1034         String sidString = ci.nextArgument();
1035         Long sid = null;
1036         if (sidString == null) {
1037             ci.println("Insert the switch id (numeric value)");
1038             return;
1039         }
1040         try {
1041             sid = Long.valueOf(sidString);
1042             this.switchSupportsVendorExtStats.put(sid, Boolean.TRUE);
1043             ci.println("Vendor capability for switch " + sid + " set to "
1044                     + this.switchSupportsVendorExtStats.get(sid));
1045         } catch (NumberFormatException e) {
1046             ci.println("Invalid switch id. Has to be numeric.");
1047         }
1048
1049     }
1050
1051     public void _ofbw(CommandInterpreter ci) {
1052         String sidString = ci.nextArgument();
1053         Long sid = null;
1054         if (sidString == null) {
1055             ci.println("Insert the switch id (numeric value)");
1056             return;
1057         }
1058         try {
1059             sid = Long.valueOf(sidString);
1060         } catch (NumberFormatException e) {
1061             ci.println("Invalid switch id. Has to be numeric.");
1062         }
1063         if (sid != null) {
1064             Map<Short, TxRates> thisSwitchRates = txRates.get(sid);
1065             ci.println("Bandwidth utilization (" + factoredSamples
1066                     * portTickNumber + " sec average) for switch "
1067                     + HexEncode.longToHexString(sid) + ":");
1068             if (thisSwitchRates == null) {
1069                 ci.println("Not available");
1070             } else {
1071                 for (Entry<Short, TxRates> entry : thisSwitchRates.entrySet()) {
1072                     ci.println("Port: " + entry.getKey() + ": "
1073                             + entry.getValue().getAverageTxRate() + " bps");
1074                 }
1075             }
1076         }
1077     }
1078
1079     public void _txratewindow(CommandInterpreter ci) {
1080         String averageWindow = ci.nextArgument();
1081         short seconds = 0;
1082         if (averageWindow == null) {
1083             ci.println("Insert the length in seconds of the median "
1084                     + "window for tx rate");
1085             ci.println("Current: " + factoredSamples * portTickNumber + " secs");
1086             return;
1087         }
1088         try {
1089             seconds = Short.valueOf(averageWindow);
1090         } catch (NumberFormatException e) {
1091             ci.println("Invalid period.");
1092         }
1093         OFStatisticsManager.factoredSamples = (short) (seconds / portTickNumber);
1094         ci.println("New: " + factoredSamples * portTickNumber + " secs");
1095     }
1096
1097     public void _ofstatsmgrintervals(CommandInterpreter ci) {
1098         String flowStatsInterv = ci.nextArgument();
1099         String portStatsInterv = ci.nextArgument();
1100         String descStatsInterv = ci.nextArgument();
1101         String tableStatsInterv = ci.nextArgument();
1102
1103         if (flowStatsInterv == null || portStatsInterv == null
1104                 || descStatsInterv == null) {
1105             ci.println("Usage: ofstatsmgrintervals <fP> <pP> <dP> <tP> (all in seconds)");
1106             ci.println("Current Values: fP=" + statisticsTickNumber + "sec pP="
1107                     + portTickNumber + "sec dP=" + descriptionTickNumber + "sec tP=" + tableTickNumber + " sec");
1108             return;
1109         }
1110         Short fP, pP, dP, tP;
1111         try {
1112             fP = Short.parseShort(flowStatsInterv);
1113             pP = Short.parseShort(portStatsInterv);
1114             dP = Short.parseShort(descStatsInterv);
1115             tP = Short.parseShort(tableStatsInterv);
1116         } catch (Exception e) {
1117             ci.println("Invalid format values: " + e.getMessage());
1118             return;
1119         }
1120
1121         if (pP <= 1 || fP <= 1 || dP <= 1 || tP <= 1) {
1122             ci.println("Invalid values. fP, pP, dP, tP have to be greater than 1.");
1123             return;
1124         }
1125
1126         statisticsTickNumber = fP;
1127         portTickNumber = pP;
1128         descriptionTickNumber = dP;
1129         tableTickNumber = tP;
1130
1131         ci.println("New Values: fP=" + statisticsTickNumber + "s pP="
1132                 + portTickNumber + "s dP=" + descriptionTickNumber + "s tP="
1133                 + tableTickNumber + "s");
1134     }
1135
1136     /**
1137      * This method retrieves user configurations from config.ini and updates
1138      * statisticsTickNumber/portTickNumber/descriptionTickNumber accordingly.
1139      */
1140     private void configStatsPollIntervals() {
1141         String fsStr = System.getProperty("of.flowStatsPollInterval");
1142         String psStr = System.getProperty("of.portStatsPollInterval");
1143         String dsStr = System.getProperty("of.descStatsPollInterval");
1144         String tsStr = System.getProperty("of.tableStatsPollInterval");
1145         Short fs, ps, ds, ts;
1146
1147         if (fsStr != null) {
1148             try {
1149                 fs = Short.parseShort(fsStr);
1150                 if (fs > 0) {
1151                     statisticsTickNumber = fs;
1152                 }
1153             } catch (Exception e) {
1154             }
1155         }
1156
1157         if (psStr != null) {
1158             try {
1159                 ps = Short.parseShort(psStr);
1160                 if (ps > 0) {
1161                     portTickNumber = ps;
1162                 }
1163             } catch (Exception e) {
1164             }
1165         }
1166
1167         if (dsStr != null) {
1168             try {
1169                 ds = Short.parseShort(dsStr);
1170                 if (ds > 0) {
1171                     descriptionTickNumber = ds;
1172                 }
1173             } catch (Exception e) {
1174             }
1175         }
1176
1177         if (tsStr != null) {
1178             try{
1179                 ts = Short.parseShort(tsStr);
1180                 if (ts > 0) {
1181                     tableTickNumber = ts;
1182                 }
1183             } catch (Exception e) {
1184             }
1185         }
1186     }
1187 }