2 * Copyright (c) 2013 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.controller.protocol_plugin.openflow.internal;
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;
18 import java.util.Map.Entry;
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;
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.connection.IPluginOutConnectionService;
40 import org.opendaylight.controller.sal.core.Node;
41 import org.opendaylight.controller.sal.core.NodeConnector;
42 import org.opendaylight.controller.sal.core.Property;
43 import org.opendaylight.controller.sal.core.UpdateType;
44 import org.opendaylight.controller.sal.utils.HexEncode;
45 import org.openflow.protocol.OFError;
46 import org.openflow.protocol.OFMatch;
47 import org.openflow.protocol.OFPort;
48 import org.openflow.protocol.OFStatisticsRequest;
49 import org.openflow.protocol.statistics.OFAggregateStatisticsRequest;
50 import org.openflow.protocol.statistics.OFFlowStatisticsReply;
51 import org.openflow.protocol.statistics.OFFlowStatisticsRequest;
52 import org.openflow.protocol.statistics.OFPortStatisticsReply;
53 import org.openflow.protocol.statistics.OFPortStatisticsRequest;
54 import org.openflow.protocol.statistics.OFQueueStatisticsRequest;
55 import org.openflow.protocol.statistics.OFStatistics;
56 import org.openflow.protocol.statistics.OFStatisticsType;
57 import org.openflow.protocol.statistics.OFTableStatistics;
58 import org.openflow.protocol.statistics.OFVendorStatistics;
59 import org.openflow.util.HexString;
60 import org.osgi.framework.BundleContext;
61 import org.osgi.framework.FrameworkUtil;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
66 * Periodically polls the different OF statistics from the OF switches, caches
67 * them, and publishes results towards SAL. It also provides an API to directly
68 * query the switch for any specific statistics.
70 public class OFStatisticsManager implements IOFStatisticsManager, 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 = new CopyOnWriteArraySet<IOFStatisticsListener>();
103 * The object containing the latest factoredSamples tx rate samples for a
106 protected class TxRates {
107 // contains the latest factoredSamples sampled transmitted bytes
108 Deque<Long> sampledTxBytes;
111 sampledTxBytes = new LinkedBlockingDeque<Long>();
114 public void update(Long txBytes) {
116 * Based on how many samples our average works on, we might have to
117 * remove the oldest sample
119 if (sampledTxBytes.size() == factoredSamples) {
120 sampledTxBytes.removeLast();
123 // Add the latest sample to the top of the queue
124 sampledTxBytes.addFirst(txBytes);
128 * Returns the average transmit rate in bps
130 * @return the average transmit rate [bps]
132 public long getAverageTxRate() {
135 * If we cannot provide the value for the time window length set
137 if (sampledTxBytes.size() < factoredSamples) {
140 long increment = sampledTxBytes.getFirst() - sampledTxBytes
142 long timePeriod = factoredSamples * PORT_STATS_PERIOD / TICK;
143 average = (8L * increment) / timePeriod;
148 public void setController(IController core) {
149 this.controller = core;
152 public void unsetController(IController core) {
153 if (this.controller == core) {
154 this.controller = null;
158 private short getStatsQueueSize() {
159 String statsQueueSizeStr = System.getProperty("of.statsQueueSize");
160 short statsQueueSize = INITIAL_SIZE;
161 if (statsQueueSizeStr != null) {
163 statsQueueSize = Short.parseShort(statsQueueSizeStr);
164 if (statsQueueSize <= 0) {
165 statsQueueSize = INITIAL_SIZE;
167 } catch (Exception e) {
170 return statsQueueSize;
173 IPluginOutConnectionService connectionPluginOutService;
174 void setIPluginOutConnectionService(IPluginOutConnectionService s) {
175 connectionPluginOutService = s;
178 void unsetIPluginOutConnectionService(IPluginOutConnectionService s) {
179 if (connectionPluginOutService == s) {
180 connectionPluginOutService = null;
185 * Function called by the dependency manager when all the required
186 * dependencies are satisfied
190 flowStatistics = new ConcurrentHashMap<Long, List<OFStatistics>>();
191 descStatistics = new ConcurrentHashMap<Long, List<OFStatistics>>();
192 portStatistics = new ConcurrentHashMap<Long, List<OFStatistics>>();
193 tableStatistics = new ConcurrentHashMap<Long, List<OFStatistics>>();
194 dummyList = new ArrayList<OFStatistics>(1);
195 pendingStatsRequests = new LinkedBlockingQueue<StatsRequest>(getStatsQueueSize());
196 statisticsTimerTicks = new ConcurrentHashMap<Long, StatisticsTicks>(INITIAL_SIZE);
197 switchPortStatsUpdated = new LinkedBlockingQueue<Long>(INITIAL_SIZE);
198 switchSupportsVendorExtStats = new ConcurrentHashMap<Long, Boolean>(INITIAL_SIZE);
199 txRates = new HashMap<Long, Map<Short, TxRates>>(INITIAL_SIZE);
201 configStatsPollIntervals();
203 // Initialize managed timers
204 statisticsTimer = new Timer("Statistics Timer Ticks");
205 statisticsTimerTask = new TimerTask() {
212 // Initialize Statistics collector thread
213 statisticsCollector = new Thread(new Runnable() {
218 StatsRequest req = pendingStatsRequests.take();
219 queryStatisticsInternal(req.switchId, req.type);
220 } catch (InterruptedException e) {
221 log.warn("Flow Statistics Collector thread "
227 }, "Statistics Collector");
229 // Initialize Tx Rate Updater thread
230 txRatesUpdater = new Thread(new Runnable() {
235 long switchId = switchPortStatsUpdated.take();
236 updatePortsTxRate(switchId);
237 } catch (InterruptedException e) {
238 log.warn("TX Rate Updater thread interrupted", e);
243 }, "TX Rate Updater");
247 * Function called by the dependency manager when at least one dependency
248 * become unsatisfied or when the component is shutting down because for
249 * example bundle is being stopped.
253 statisticsListeners.clear();
257 * Function called by dependency manager after "init ()" is called and after
258 * the services provided by the class are registered in the service registry
262 // Start managed timers
263 statisticsTimer.scheduleAtFixedRate(statisticsTimerTask, 0, TICK);
265 // Start statistics collector thread
266 statisticsCollector.start();
268 // Start bandwidth utilization computer thread
269 txRatesUpdater.start();
272 registerWithOSGIConsole();
276 * Function called by the dependency manager before the services exported by
277 * the component are unregistered, this will be followed by a "destroy ()"
282 // Stop managed timers
283 statisticsTimer.cancel();
286 public void setStatisticsListener(IOFStatisticsListener s) {
287 this.statisticsListeners.add(s);
290 public void unsetStatisticsListener(IOFStatisticsListener s) {
292 this.statisticsListeners.remove(s);
296 private void registerWithOSGIConsole() {
297 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
298 bundleContext.registerService(CommandProvider.class.getName(), this, null);
301 private static class StatsRequest {
302 protected Long switchId;
303 protected OFStatisticsType type;
305 public StatsRequest(Long d, OFStatisticsType t) {
311 public String toString() {
312 return "SReq = {switchId=" + switchId + ", type=" + type + "}";
316 public int hashCode() {
317 final int prime = 31;
319 result = prime * result
320 + ((switchId == null) ? 0 : switchId.hashCode());
321 result = prime * result + ((type == null) ? 0 : type.ordinal());
326 public boolean equals(Object obj) {
333 if (getClass() != obj.getClass()) {
336 StatsRequest other = (StatsRequest) obj;
337 if (switchId == null) {
338 if (other.switchId != null) {
341 } else if (!switchId.equals(other.switchId)) {
344 if (type != other.type) {
351 private void addStatisticsTicks(Long switchId) {
352 switchSupportsVendorExtStats.put(switchId, Boolean.TRUE); // Assume
358 statisticsTimerTicks.put(switchId, new StatisticsTicks(true));
359 log.debug("Added Switch {} to target pool",
360 HexString.toHexString(switchId.longValue()));
363 protected static class StatisticsTicks {
364 private short flowStatisticsTicks;
365 private short descriptionTicks;
366 private short portStatisticsTicks;
367 private short tableStatisticsTicks;
369 public StatisticsTicks(boolean scattered) {
371 // scatter bursts by statisticsTickPeriod
374 } // being paranoid here
375 flowStatisticsTicks = (short) (1 + counter
376 % statisticsTickNumber);
377 descriptionTicks = (short) (1 + counter % descriptionTickNumber);
378 portStatisticsTicks = (short) (1 + counter % portTickNumber);
379 tableStatisticsTicks = (short) (1 + counter % tableTickNumber);
381 flowStatisticsTicks = statisticsTickNumber;
382 descriptionTicks = descriptionTickNumber;
383 portStatisticsTicks = portTickNumber;
384 tableStatisticsTicks = tableTickNumber;
388 public boolean decrementFlowTicksIsZero() {
389 // Please ensure no code is inserted between the if check and the
390 // flowStatisticsTicks reset
391 if (--flowStatisticsTicks == 0) {
392 flowStatisticsTicks = statisticsTickNumber;
398 public boolean decrementDescTicksIsZero() {
399 // Please ensure no code is inserted between the if check and the
400 // descriptionTicks reset
401 if (--descriptionTicks == 0) {
402 descriptionTicks = descriptionTickNumber;
408 public boolean decrementPortTicksIsZero() {
409 // Please ensure no code is inserted between the if check and the
410 // descriptionTicks reset
411 if (--portStatisticsTicks == 0) {
412 portStatisticsTicks = portTickNumber;
418 public boolean decrementTableTicksIsZero() {
419 // Please ensure no code is inserted between the if check and the
420 // descriptionTicks reset
421 if(--tableStatisticsTicks == 0) {
422 tableStatisticsTicks = tableTickNumber;
429 public String toString() {
430 return "{fT=" + flowStatisticsTicks + ",dT=" + descriptionTicks
431 + ",pT=" + portStatisticsTicks + ",tT=" + tableStatisticsTicks + "}";
435 private void printInfoMessage(String type, StatsRequest request) {
436 log.info("{} stats request not inserted for switch: {}. Queue size: {}. Collector state: {}.",
437 new Object[] {type, HexString.toHexString(request.switchId), pendingStatsRequests.size(),
438 statisticsCollector.getState().toString() });
441 protected void decrementTicks() {
442 StatsRequest request = null;
443 for (Map.Entry<Long, StatisticsTicks> entry : statisticsTimerTicks
445 StatisticsTicks clock = entry.getValue();
446 Long switchId = entry.getKey();
447 if (clock.decrementFlowTicksIsZero()) {
448 request = (switchSupportsVendorExtStats.get(switchId) == Boolean.TRUE) ?
449 new StatsRequest(switchId, OFStatisticsType.VENDOR) :
450 new StatsRequest(switchId, OFStatisticsType.FLOW);
451 // If a request for this switch is already in the queue, skip to
452 // add this new request
453 if (!pendingStatsRequests.contains(request)
454 && false == pendingStatsRequests.offer(request)) {
455 printInfoMessage("Flow", request);
459 if (clock.decrementDescTicksIsZero()) {
460 request = new StatsRequest(switchId, OFStatisticsType.DESC);
461 // If a request for this switch is already in the queue, skip to
462 // add this new request
463 if (!pendingStatsRequests.contains(request)
464 && false == pendingStatsRequests.offer(request)) {
465 printInfoMessage("Description", request);
469 if (clock.decrementPortTicksIsZero()) {
470 request = new StatsRequest(switchId, OFStatisticsType.PORT);
471 // If a request for this switch is already in the queue, skip to
472 // add this new request
473 if (!pendingStatsRequests.contains(request)
474 && false == pendingStatsRequests.offer(request)) {
475 printInfoMessage("Port", request);
479 if(clock.decrementTableTicksIsZero()) {
480 request = new StatsRequest(switchId, OFStatisticsType.TABLE);
481 // If a request for this switch is already in the queue, skip to
482 // add this new request
483 if (!pendingStatsRequests.contains(request)
484 && false == pendingStatsRequests.offer(request)) {
485 printInfoMessage("Table", request);
491 private void removeStatsRequestTasks(Long switchId) {
492 log.debug("Cleaning Statistics database for switch {}",
493 HexEncode.longToHexString(switchId));
494 // To be safe, let's attempt removal of both VENDOR and FLOW request. It
496 pendingStatsRequests.remove(new StatsRequest(switchId,
497 OFStatisticsType.VENDOR));
498 pendingStatsRequests.remove(new StatsRequest(switchId,
499 OFStatisticsType.FLOW));
500 pendingStatsRequests.remove(new StatsRequest(switchId,
501 OFStatisticsType.DESC));
502 pendingStatsRequests.remove(new StatsRequest(switchId,
503 OFStatisticsType.PORT));
504 pendingStatsRequests.remove(new StatsRequest(switchId,
505 OFStatisticsType.TABLE));
506 // Take care of the TX rate databases
507 switchPortStatsUpdated.remove(switchId);
508 txRates.remove(switchId);
511 private void clearFlowStatsAndTicks(Long switchId) {
512 statisticsTimerTicks.remove(switchId);
513 removeStatsRequestTasks(switchId);
514 flowStatistics.remove(switchId);
515 log.debug("Statistics removed for switch {}",
516 HexString.toHexString(switchId));
519 private void queryStatisticsInternal(Long switchId, OFStatisticsType statType) {
521 // Query the switch on all matches
522 List<OFStatistics> values = this.fetchStatisticsFromSwitch(switchId, statType, null);
524 // If got a valid response update local cache and notify listeners
525 if (values != null && !values.isEmpty()) {
529 flowStatistics.put(switchId, values);
530 notifyFlowUpdate(switchId, values);
534 descStatistics.put(switchId, values);
535 // Notify who may be interested in a description change
536 notifyDescriptionUpdate(switchId, values);
539 // Overwrite cache with new port statistics for this switch
540 portStatistics.put(switchId, values);
542 // Wake up the thread which maintains the TX byte counters for
544 switchPortStatsUpdated.offer(switchId);
545 notifyPortUpdate(switchId, values);
549 tableStatistics.put(switchId, values);
550 notifyTableUpdate(switchId, values);
557 private void notifyDescriptionUpdate(Long switchId, List<OFStatistics> values) {
558 for (IOFStatisticsListener l : this.statisticsListeners) {
559 l.descriptionStatisticsRefreshed(switchId, values);
563 private void notifyFlowUpdate(Long switchId, List<OFStatistics> values) {
564 if (values.get(0) instanceof OFVendorStatistics) {
565 values = this.v6StatsListToOFStatsList(values);
568 for (IOFStatisticsListener l : this.statisticsListeners) {
569 l.flowStatisticsRefreshed(switchId, values);
574 private void notifyPortUpdate(Long switchId, List<OFStatistics> values) {
575 for (IOFStatisticsListener l : this.statisticsListeners) {
576 l.portStatisticsRefreshed(switchId, values);
580 private void notifyTableUpdate(Long switchId, List<OFStatistics> values) {
581 for (IOFStatisticsListener l : this.statisticsListeners) {
582 l.tableStatisticsRefreshed(switchId, values);
587 * Generic function to get the statistics form an OF switch
589 @SuppressWarnings("unchecked")
590 private List<OFStatistics> fetchStatisticsFromSwitch(Long switchId,
591 OFStatisticsType statsType, Object target) {
592 List<OFStatistics> values = null;
594 ISwitch sw = controller.getSwitch(switchId);
597 OFStatisticsRequest req = new OFStatisticsRequest();
598 req.setStatisticType(statsType);
599 int requestLength = req.getLengthU();
601 if (statsType == OFStatisticsType.FLOW) {
602 OFMatch match = null;
603 if (target == null) {
605 match = new OFMatch();
606 match.setWildcards(0xffffffff);
607 } else if (!(target instanceof OFMatch)) {
609 log.warn("Invalid target type for Flow stats request: {}",
613 // Specific flow request
614 match = (OFMatch) target;
616 OFFlowStatisticsRequest specificReq = new OFFlowStatisticsRequest();
617 specificReq.setMatch(match);
618 specificReq.setOutPort(OFPort.OFPP_NONE.getValue());
619 specificReq.setTableId((byte) 0xff);
620 req.setStatistics(Collections
621 .singletonList((OFStatistics) specificReq));
622 requestLength += specificReq.getLength();
624 } else if (statsType == OFStatisticsType.VENDOR) {
625 V6StatsRequest specificReq = new V6StatsRequest();
626 specificReq.setOutPort(OFPort.OFPP_NONE.getValue());
627 specificReq.setTableId((byte) 0xff);
628 req.setStatistics(Collections
629 .singletonList((OFStatistics) specificReq));
630 requestLength += specificReq.getLength();
632 } else if (statsType == OFStatisticsType.AGGREGATE) {
633 OFAggregateStatisticsRequest specificReq = new OFAggregateStatisticsRequest();
634 OFMatch match = new OFMatch();
635 match.setWildcards(0xffffffff);
636 specificReq.setMatch(match);
637 specificReq.setOutPort(OFPort.OFPP_NONE.getValue());
638 specificReq.setTableId((byte) 0xff);
639 req.setStatistics(Collections
640 .singletonList((OFStatistics) specificReq));
641 requestLength += specificReq.getLength();
643 } else if (statsType == OFStatisticsType.PORT) {
645 if (target == null) {
647 targetPort = OFPort.OFPP_NONE.getValue();
648 } else if (!(target instanceof Short)) {
650 log.warn("Invalid target type for Port stats request: {}",
654 // Specific port request
655 targetPort = (Short) target;
657 OFPortStatisticsRequest specificReq = new OFPortStatisticsRequest();
658 specificReq.setPortNumber(targetPort);
659 req.setStatistics(Collections
660 .singletonList((OFStatistics) specificReq));
661 requestLength += specificReq.getLength();
663 } else if (statsType == OFStatisticsType.QUEUE) {
664 OFQueueStatisticsRequest specificReq = new OFQueueStatisticsRequest();
665 specificReq.setPortNumber(OFPort.OFPP_ALL.getValue());
666 specificReq.setQueueId(0xffffffff);
667 req.setStatistics(Collections
668 .singletonList((OFStatistics) specificReq));
669 requestLength += specificReq.getLength();
671 } else if (statsType == OFStatisticsType.DESC) {
673 } else if (statsType == OFStatisticsType.TABLE) {
675 if (!(target instanceof Byte)) {
677 log.warn("Invalid table id for table stats request: {}",
681 byte targetTable = (Byte) target;
682 OFTableStatistics specificReq = new OFTableStatistics();
683 specificReq.setTableId(targetTable);
684 req.setStatistics(Collections
685 .singletonList((OFStatistics) specificReq));
686 requestLength += specificReq.getLength();
690 req.setLengthU(requestLength);
691 Object result = sw.getStatistics(req);
693 if (result == null) {
694 log.warn("Request Timed Out for ({}) from switch {}", type,
695 HexString.toHexString(switchId));
696 } else if (result instanceof OFError) {
697 log.warn("Switch {} failed to handle ({}) stats request: {}",
698 new Object[] { HexString.toHexString(switchId), type,
699 Utils.getOFErrorString((OFError) result) });
700 if (this.switchSupportsVendorExtStats.get(switchId) == Boolean.TRUE) {
702 "Switching back to regular Flow stats requests for switch {}",
703 HexString.toHexString(switchId));
704 this.switchSupportsVendorExtStats.put(switchId,
708 values = (List<OFStatistics>) result;
715 public List<OFStatistics> getOFFlowStatistics(Long switchId) {
716 List<OFStatistics> list = flowStatistics.get(switchId);
719 * Check on emptiness as interference between add and get is still
720 * possible on the inner list (the concurrentMap entry's value)
722 return (list == null || list.isEmpty()) ? this.dummyList
723 : (list.get(0) instanceof OFVendorStatistics) ? this
724 .v6StatsListToOFStatsList(list) : list;
728 public List<OFStatistics> getOFFlowStatistics(Long switchId, OFMatch ofMatch, short priority) {
729 List<OFStatistics> statsList = flowStatistics.get(switchId);
732 * Check on emptiness as interference between add and get is still
733 * possible on the inner list (the concurrentMap entry's value)
735 if (statsList == null || statsList.isEmpty()) {
736 return this.dummyList;
739 if (statsList.get(0) instanceof OFVendorStatistics) {
741 * Caller could provide regular OF match when we instead pull the
742 * vendor statistics from this node Caller is not supposed to know
743 * whether this switch supports vendor extensions statistics
746 V6Match targetMatch = (ofMatch instanceof V6Match) ? (V6Match) ofMatch
747 : new V6Match(ofMatch);
749 List<OFStatistics> targetList = v6StatsListToOFStatsList(statsList);
750 for (OFStatistics stats : targetList) {
751 V6StatsReply v6Stats = (V6StatsReply) stats;
752 V6Match v6Match = v6Stats.getMatch();
753 if (v6Stats.getPriority() == priority && v6Match.equals(targetMatch)) {
754 List<OFStatistics> list = new ArrayList<OFStatistics>();
760 for (OFStatistics stats : statsList) {
761 OFFlowStatisticsReply flowStats = (OFFlowStatisticsReply) stats;
762 if (flowStats.getPriority() == priority && flowStats.getMatch().equals(ofMatch)) {
763 List<OFStatistics> list = new ArrayList<OFStatistics>();
769 return this.dummyList;
773 * Converts the v6 vendor statistics to the OFStatistics
775 private List<OFStatistics> v6StatsListToOFStatsList(
776 List<OFStatistics> statistics) {
777 List<OFStatistics> v6statistics = new ArrayList<OFStatistics>();
778 if (statistics != null && !statistics.isEmpty()) {
779 for (OFStatistics stats : statistics) {
780 if (stats instanceof OFVendorStatistics) {
781 List<OFStatistics> r = getV6ReplyStatistics((OFVendorStatistics) stats);
783 v6statistics.addAll(r);
791 private static List<OFStatistics> getV6ReplyStatistics(
792 OFVendorStatistics stat) {
793 int length = stat.getLength();
794 List<OFStatistics> results = new ArrayList<OFStatistics>();
796 return null; // Nicira Hdr is 12 bytes. We need atleast that much
797 ByteBuffer data = ByteBuffer.allocate(length);
800 if (log.isTraceEnabled()) {
801 log.trace("getV6ReplyStatistics: Buffer BYTES ARE {}",
802 HexString.toHexString(data.array()));
805 int vendor = data.getInt(); // first 4 bytes is vendor id.
806 if (vendor != V6StatsRequest.NICIRA_VENDOR_ID) {
807 log.warn("Unexpected vendor id: 0x{}", Integer.toHexString(vendor));
810 // go ahead by 8 bytes which is 8 bytes of 0
811 data.getLong(); // should be all 0's
812 length -= 12; // 4 bytes Nicira Hdr + 8 bytes from above line have
816 V6StatsReply v6statsreply;
819 v6statsreply = new V6StatsReply();
820 min_len = v6statsreply.getLength();
821 if (length < v6statsreply.getLength())
823 v6statsreply.setActionFactory(stat.getActionFactory());
824 v6statsreply.readFrom(data);
825 if (v6statsreply.getLength() < min_len)
827 v6statsreply.setVendorId(vendor);
828 log.trace("V6StatsReply: {}", v6statsreply);
829 length -= v6statsreply.getLength();
830 results.add(v6statsreply);
836 public List<OFStatistics> queryStatistics(Long switchId,
837 OFStatisticsType statType, Object target) {
839 * Caller does not know and it is not supposed to know whether this
840 * switch supports vendor extension. We adjust the target for him
842 if (statType == OFStatisticsType.FLOW) {
843 if (switchSupportsVendorExtStats.get(switchId) == Boolean.TRUE) {
844 statType = OFStatisticsType.VENDOR;
848 List<OFStatistics> list = this.fetchStatisticsFromSwitch(switchId, statType,
851 return (list == null) ? null :
852 (statType == OFStatisticsType.VENDOR) ? v6StatsListToOFStatsList(list) : list;
856 public List<OFStatistics> getOFDescStatistics(Long switchId) {
857 if (!descStatistics.containsKey(switchId))
858 return this.dummyList;
860 return descStatistics.get(switchId);
864 public List<OFStatistics> getOFPortStatistics(Long switchId) {
865 if (!portStatistics.containsKey(switchId)) {
866 return this.dummyList;
869 return portStatistics.get(switchId);
873 public List<OFStatistics> getOFPortStatistics(Long switchId, short portId) {
874 if (!portStatistics.containsKey(switchId)) {
875 return this.dummyList;
877 List<OFStatistics> list = new ArrayList<OFStatistics>(1);
878 for (OFStatistics stats : portStatistics.get(switchId)) {
879 if (((OFPortStatisticsReply) stats).getPortNumber() == portId) {
888 public List<OFStatistics> getOFTableStatistics(Long switchId) {
889 if (!tableStatistics.containsKey(switchId)) {
890 return this.dummyList;
893 return tableStatistics.get(switchId);
897 public List<OFStatistics> getOFTableStatistics(Long switchId, Byte tableId) {
898 if (!tableStatistics.containsKey(switchId)) {
899 return this.dummyList;
902 List<OFStatistics> list = new ArrayList<OFStatistics>(1);
903 for (OFStatistics stats : tableStatistics.get(switchId)) {
904 if (((OFTableStatistics) stats).getTableId() == tableId) {
913 public int getFlowsNumber(long switchId) {
914 return this.flowStatistics.get(switchId).size();
918 * InventoryShim replay for us all the switch addition which happened before
922 public void updateNode(Node node, UpdateType type, Set<Property> props) {
923 Long switchId = (Long) node.getID();
926 addStatisticsTicks(switchId);
929 clearFlowStatsAndTicks(switchId);
935 public void updateNodeConnector(NodeConnector nodeConnector,
936 UpdateType type, Set<Property> props) {
941 * Update the cached port rates for this switch with the latest retrieved
942 * port transmit byte count
946 private synchronized void updatePortsTxRate(long switchId) {
947 List<OFStatistics> newPortStatistics = this.portStatistics.get(switchId);
948 if (newPortStatistics == null) {
951 Map<Short, TxRates> rates = this.txRates.get(switchId);
953 // First time rates for this switch are added
954 rates = new HashMap<Short, TxRates>();
955 txRates.put(switchId, rates);
957 for (OFStatistics stats : newPortStatistics) {
958 OFPortStatisticsReply newPortStat = (OFPortStatisticsReply) stats;
959 short port = newPortStat.getPortNumber();
960 TxRates portRatesHolder = rates.get(port);
961 if (portRatesHolder == null) {
962 // First time rates for this port are added
963 portRatesHolder = new TxRates();
964 rates.put(port, portRatesHolder);
966 // Get and store the number of transmitted bytes for this port
967 // And handle the case where agent does not support the counter
968 long transmitBytes = newPortStat.getTransmitBytes();
969 long value = (transmitBytes < 0) ? 0 : transmitBytes;
970 portRatesHolder.update(value);
975 public synchronized long getTransmitRate(Long switchId, Short port) {
977 if (switchId == null || port == null) {
980 Map<Short, TxRates> perSwitch = txRates.get(switchId);
981 if (perSwitch == null) {
984 TxRates portRates = perSwitch.get(port);
985 if (portRates == null) {
988 return portRates.getAverageTxRate();
992 * Manual switch name configuration code
995 public String getHelp() {
996 StringBuffer help = new StringBuffer();
997 help.append("---OF Statistics Manager utilities---\n");
998 help.append("\t ofdumpstatsmgr - "
999 + "Print Internal Stats Mgr db\n");
1000 help.append("\t ofstatsmgrintervals <fP> <pP> <dP> <tP> (all in seconds) - "
1001 + "Set/Show flow/port/dedscription stats poll intervals\n");
1002 return help.toString();
1005 private boolean isValidSwitchId(String switchId) {
1006 String regexDatapathID = "^([0-9a-fA-F]{1,2}[:-]){7}[0-9a-fA-F]{1,2}$";
1007 String regexDatapathIDLong = "^[0-9a-fA-F]{1,16}$";
1009 return (switchId != null && (switchId.matches(regexDatapathID) || switchId
1010 .matches(regexDatapathIDLong)));
1013 public long getSwitchIDLong(String switchId) {
1015 String switchString = "0";
1017 if (isValidSwitchId(switchId)) {
1018 if (switchId.contains(":")) {
1019 // Handle the 00:00:AA:BB:CC:DD:EE:FF notation
1020 switchString = switchId.replace(":", "");
1021 } else if (switchId.contains("-")) {
1022 // Handle the 00-00-AA-BB-CC-DD-EE-FF notation
1023 switchString = switchId.replace("-", "");
1025 // Handle the 0123456789ABCDEF notation
1026 switchString = switchId;
1029 return Long.parseLong(switchString, radix);
1033 * Internal information dump code
1035 private String prettyPrintSwitchMap(ConcurrentMap<Long, StatisticsTicks> map) {
1036 StringBuffer buffer = new StringBuffer();
1038 for (Entry<Long, StatisticsTicks> entry : map.entrySet()) {
1039 buffer.append(HexString.toHexString(entry.getKey()) + "="
1040 + entry.getValue().toString() + " ");
1043 return buffer.toString();
1046 public void _ofdumpstatsmgr(CommandInterpreter ci) {
1047 ci.println("Global Counter: " + counter);
1048 ci.println("Timer Ticks: " + prettyPrintSwitchMap(statisticsTimerTicks));
1049 ci.println("PendingStatsQueue: " + pendingStatsRequests);
1050 ci.println("PendingStatsQueue size: " + pendingStatsRequests.size());
1051 ci.println("Stats Collector alive: " + statisticsCollector.isAlive());
1052 ci.println("Stats Collector State: "
1053 + statisticsCollector.getState().toString());
1054 ci.println("StatsTimer: " + statisticsTimer.toString());
1055 ci.println("Flow Stats Period: " + statisticsTickNumber + " s");
1056 ci.println("Desc Stats Period: " + descriptionTickNumber + " s");
1057 ci.println("Port Stats Period: " + portTickNumber + " s");
1058 ci.println("Table Stats Period: " + tableTickNumber + " s");
1061 public void _resetSwitchCapability(CommandInterpreter ci) {
1062 String sidString = ci.nextArgument();
1064 if (sidString == null) {
1065 ci.println("Insert the switch id (numeric value)");
1069 sid = Long.valueOf(sidString);
1070 this.switchSupportsVendorExtStats.put(sid, Boolean.TRUE);
1071 ci.println("Vendor capability for switch " + sid + " set to "
1072 + this.switchSupportsVendorExtStats.get(sid));
1073 } catch (NumberFormatException e) {
1074 ci.println("Invalid switch id. Has to be numeric.");
1079 public void _ofbw(CommandInterpreter ci) {
1080 String sidString = ci.nextArgument();
1082 if (sidString == null) {
1083 ci.println("Insert the switch id (numeric value)");
1087 sid = Long.valueOf(sidString);
1088 } catch (NumberFormatException e) {
1089 ci.println("Invalid switch id. Has to be numeric.");
1092 Map<Short, TxRates> thisSwitchRates = txRates.get(sid);
1093 ci.println("Bandwidth utilization (" + factoredSamples
1094 * portTickNumber + " sec average) for switch "
1095 + HexEncode.longToHexString(sid) + ":");
1096 if (thisSwitchRates == null) {
1097 ci.println("Not available");
1099 for (Entry<Short, TxRates> entry : thisSwitchRates.entrySet()) {
1100 ci.println("Port: " + entry.getKey() + ": "
1101 + entry.getValue().getAverageTxRate() + " bps");
1107 public void _txratewindow(CommandInterpreter ci) {
1108 String averageWindow = ci.nextArgument();
1110 if (averageWindow == null) {
1111 ci.println("Insert the length in seconds of the median "
1112 + "window for tx rate");
1113 ci.println("Current: " + factoredSamples * portTickNumber + " secs");
1117 seconds = Short.valueOf(averageWindow);
1118 } catch (NumberFormatException e) {
1119 ci.println("Invalid period.");
1121 OFStatisticsManager.factoredSamples = (short) (seconds / portTickNumber);
1122 ci.println("New: " + factoredSamples * portTickNumber + " secs");
1125 public void _ofstatsmgrintervals(CommandInterpreter ci) {
1126 String flowStatsInterv = ci.nextArgument();
1127 String portStatsInterv = ci.nextArgument();
1128 String descStatsInterv = ci.nextArgument();
1129 String tableStatsInterv = ci.nextArgument();
1131 if (flowStatsInterv == null || portStatsInterv == null
1132 || descStatsInterv == null) {
1133 ci.println("Usage: ofstatsmgrintervals <fP> <pP> <dP> <tP> (all in seconds)");
1134 ci.println("Current Values: fP=" + statisticsTickNumber + "sec pP="
1135 + portTickNumber + "sec dP=" + descriptionTickNumber + "sec tP=" + tableTickNumber + " sec");
1138 Short fP, pP, dP, tP;
1140 fP = Short.parseShort(flowStatsInterv);
1141 pP = Short.parseShort(portStatsInterv);
1142 dP = Short.parseShort(descStatsInterv);
1143 tP = Short.parseShort(tableStatsInterv);
1144 } catch (Exception e) {
1145 ci.println("Invalid format values: " + e.getMessage());
1149 if (pP <= 1 || fP <= 1 || dP <= 1 || tP <= 1) {
1150 ci.println("Invalid values. fP, pP, dP, tP have to be greater than 1.");
1154 statisticsTickNumber = fP;
1155 portTickNumber = pP;
1156 descriptionTickNumber = dP;
1157 tableTickNumber = tP;
1159 ci.println("New Values: fP=" + statisticsTickNumber + "s pP="
1160 + portTickNumber + "s dP=" + descriptionTickNumber + "s tP="
1161 + tableTickNumber + "s");
1165 * This method retrieves user configurations from config.ini and updates
1166 * statisticsTickNumber/portTickNumber/descriptionTickNumber accordingly.
1168 private void configStatsPollIntervals() {
1169 String fsStr = System.getProperty("of.flowStatsPollInterval");
1170 String psStr = System.getProperty("of.portStatsPollInterval");
1171 String dsStr = System.getProperty("of.descStatsPollInterval");
1172 String tsStr = System.getProperty("of.tableStatsPollInterval");
1173 Short fs, ps, ds, ts;
1175 if (fsStr != null) {
1177 fs = Short.parseShort(fsStr);
1179 statisticsTickNumber = fs;
1181 } catch (Exception e) {
1185 if (psStr != null) {
1187 ps = Short.parseShort(psStr);
1189 portTickNumber = ps;
1191 } catch (Exception e) {
1195 if (dsStr != null) {
1197 ds = Short.parseShort(dsStr);
1199 descriptionTickNumber = ds;
1201 } catch (Exception e) {
1205 if (tsStr != null) {
1207 ts = Short.parseShort(tsStr);
1209 tableTickNumber = ts;
1211 } catch (Exception e) {