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.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;
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
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;
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;
159 * Function called by the dependency manager when all the required
160 * dependencies are satisfied
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>();
176 configStatsPollIntervals();
178 // Initialize managed timers
179 statisticsTimer = new Timer();
180 statisticsTimerTask = new TimerTask() {
187 // Initialize Statistics collector thread
188 statisticsCollector = new Thread(new Runnable() {
193 StatsRequest req = pendingStatsRequests.take();
194 queryStatisticsInternal(req.switchId, req.type);
195 } catch (InterruptedException e) {
196 log.warn("Flow Statistics Collector thread "
201 }, "Statistics Collector");
203 // Initialize Tx Rate Updater thread
204 txRatesUpdater = new Thread(new Runnable() {
209 long switchId = switchPortStatsUpdated.take();
210 updatePortsTxRate(switchId);
211 } catch (InterruptedException e) {
212 log.warn("TX Rate Updater thread interrupted", e);
216 }, "TX Rate Updater");
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.
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
234 // Start managed timers
235 statisticsTimer.scheduleAtFixedRate(statisticsTimerTask, 0, TICK);
237 // Start statistics collector thread
238 statisticsCollector.start();
240 // Start bandwidth utilization computer thread
241 txRatesUpdater.start();
244 registerWithOSGIConsole();
248 * Function called by the dependency manager before the services exported by
249 * the component are unregistered, this will be followed by a "destroy ()"
254 // Stop managed timers
255 statisticsTimer.cancel();
258 public void setStatisticsListener(IOFStatisticsListener s) {
259 this.statisticsListeners.add(s);
262 public void unsetStatisticsListener(IOFStatisticsListener s) {
264 this.statisticsListeners.remove(s);
268 private void registerWithOSGIConsole() {
269 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
270 bundleContext.registerService(CommandProvider.class.getName(), this, null);
273 private static class StatsRequest {
274 protected Long switchId;
275 protected OFStatisticsType type;
277 public StatsRequest(Long d, OFStatisticsType t) {
283 public String toString() {
284 return "SReq = {switchId=" + switchId + ", type=" + type + "}";
288 public int hashCode() {
289 final int prime = 31;
291 result = prime * result
292 + ((switchId == null) ? 0 : switchId.hashCode());
293 result = prime * result + ((type == null) ? 0 : type.ordinal());
298 public boolean equals(Object obj) {
305 if (getClass() != obj.getClass()) {
308 StatsRequest other = (StatsRequest) obj;
309 if (switchId == null) {
310 if (other.switchId != null) {
313 } else if (!switchId.equals(other.switchId)) {
316 if (type != other.type) {
323 private void addStatisticsTicks(Long switchId) {
324 switchSupportsVendorExtStats.put(switchId, Boolean.TRUE); // Assume
330 statisticsTimerTicks.put(switchId, new StatisticsTicks(true));
331 log.debug("Added Switch {} to target pool",
332 HexString.toHexString(switchId.longValue()));
335 protected static class StatisticsTicks {
336 private short flowStatisticsTicks;
337 private short descriptionTicks;
338 private short portStatisticsTicks;
339 private short tableStatisticsTicks;
341 public StatisticsTicks(boolean scattered) {
343 // scatter bursts by statisticsTickPeriod
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);
353 flowStatisticsTicks = statisticsTickNumber;
354 descriptionTicks = descriptionTickNumber;
355 portStatisticsTicks = portTickNumber;
356 tableStatisticsTicks = tableTickNumber;
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;
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;
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;
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;
401 public String toString() {
402 return "{fT=" + flowStatisticsTicks + ",dT=" + descriptionTicks
403 + ",pT=" + portStatisticsTicks + ",tT=" + tableStatisticsTicks + "}";
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() });
413 protected void decrementTicks() {
414 StatsRequest request = null;
415 for (Map.Entry<Long, StatisticsTicks> entry : statisticsTimerTicks
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);
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);
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);
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);
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
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);
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));
491 private void queryStatisticsInternal(Long switchId, OFStatisticsType statType) {
493 // Query the switch on all matches
494 List<OFStatistics> values = this.fetchStatisticsFromSwitch(switchId, statType, null);
496 // If got a valid response update local cache and notify listeners
497 if (values != null && !values.isEmpty()) {
501 flowStatistics.put(switchId, values);
502 notifyFlowUpdate(switchId, values);
506 descStatistics.put(switchId, values);
507 // Notify who may be interested in a description change
508 notifyDescriptionUpdate(switchId, values);
511 // Overwrite cache with new port statistics for this switch
512 portStatistics.put(switchId, values);
514 // Wake up the thread which maintains the TX byte counters for
516 switchPortStatsUpdated.offer(switchId);
517 notifyPortUpdate(switchId, values);
521 tableStatistics.put(switchId, values);
522 notifyTableUpdate(switchId, values);
529 private void notifyDescriptionUpdate(Long switchId, List<OFStatistics> values) {
530 for (IOFStatisticsListener l : this.statisticsListeners) {
531 l.descriptionStatisticsRefreshed(switchId, values);
535 private void notifyFlowUpdate(Long switchId, List<OFStatistics> values) {
536 if (values.get(0) instanceof OFVendorStatistics) {
537 values = this.v6StatsListToOFStatsList(values);
540 for (IOFStatisticsListener l : this.statisticsListeners) {
541 l.flowStatisticsRefreshed(switchId, values);
546 private void notifyPortUpdate(Long switchId, List<OFStatistics> values) {
547 for (IOFStatisticsListener l : this.statisticsListeners) {
548 l.portStatisticsRefreshed(switchId, values);
552 private void notifyTableUpdate(Long switchId, List<OFStatistics> values) {
553 for (IOFStatisticsListener l : this.statisticsListeners) {
554 l.tableStatisticsRefreshed(switchId, values);
559 * Generic function to get the statistics form an OF switch
561 @SuppressWarnings("unchecked")
562 private List<OFStatistics> fetchStatisticsFromSwitch(Long switchId,
563 OFStatisticsType statsType, Object target) {
564 List<OFStatistics> values = null;
566 ISwitch sw = controller.getSwitch(switchId);
569 OFStatisticsRequest req = new OFStatisticsRequest();
570 req.setStatisticType(statsType);
571 int requestLength = req.getLengthU();
573 if (statsType == OFStatisticsType.FLOW) {
574 OFMatch match = null;
575 if (target == null) {
577 match = new OFMatch();
578 match.setWildcards(0xffffffff);
579 } else if (!(target instanceof OFMatch)) {
581 log.warn("Invalid target type for Flow stats request: {}",
585 // Specific flow request
586 match = (OFMatch) target;
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();
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();
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();
615 } else if (statsType == OFStatisticsType.PORT) {
617 if (target == null) {
619 targetPort = OFPort.OFPP_NONE.getValue();
620 } else if (!(target instanceof Short)) {
622 log.warn("Invalid target type for Port stats request: {}",
626 // Specific port request
627 targetPort = (Short) target;
629 OFPortStatisticsRequest specificReq = new OFPortStatisticsRequest();
630 specificReq.setPortNumber(targetPort);
631 req.setStatistics(Collections
632 .singletonList((OFStatistics) specificReq));
633 requestLength += specificReq.getLength();
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();
643 } else if (statsType == OFStatisticsType.DESC) {
645 } else if (statsType == OFStatisticsType.TABLE) {
647 if (!(target instanceof Byte)) {
649 log.warn("Invalid table id for table stats request: {}",
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();
662 req.setLengthU(requestLength);
663 Object result = sw.getStatistics(req);
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) {
674 "Switching back to regular Flow stats requests for switch {}",
675 HexString.toHexString(switchId));
676 this.switchSupportsVendorExtStats.put(switchId,
680 values = (List<OFStatistics>) result;
687 public List<OFStatistics> getOFFlowStatistics(Long switchId) {
688 List<OFStatistics> list = flowStatistics.get(switchId);
691 * Check on emptiness as interference between add and get is still
692 * possible on the inner list (the concurrentMap entry's value)
694 return (list == null || list.isEmpty()) ? this.dummyList
695 : (list.get(0) instanceof OFVendorStatistics) ? this
696 .v6StatsListToOFStatsList(list) : list;
700 public List<OFStatistics> getOFFlowStatistics(Long switchId, OFMatch ofMatch, short priority) {
701 List<OFStatistics> statsList = flowStatistics.get(switchId);
704 * Check on emptiness as interference between add and get is still
705 * possible on the inner list (the concurrentMap entry's value)
707 if (statsList == null || statsList.isEmpty()) {
708 return this.dummyList;
711 if (statsList.get(0) instanceof OFVendorStatistics) {
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
718 V6Match targetMatch = (ofMatch instanceof V6Match) ? (V6Match) ofMatch
719 : new V6Match(ofMatch);
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>();
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>();
741 return this.dummyList;
745 * Converts the v6 vendor statistics to the OFStatistics
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);
755 v6statistics.addAll(r);
763 private static List<OFStatistics> getV6ReplyStatistics(
764 OFVendorStatistics stat) {
765 int length = stat.getLength();
766 List<OFStatistics> results = new ArrayList<OFStatistics>();
768 return null; // Nicira Hdr is 12 bytes. We need atleast that much
769 ByteBuffer data = ByteBuffer.allocate(length);
772 if (log.isTraceEnabled()) {
773 log.trace("getV6ReplyStatistics: Buffer BYTES ARE {}",
774 HexString.toHexString(data.array()));
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));
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
788 V6StatsReply v6statsreply;
791 v6statsreply = new V6StatsReply();
792 min_len = v6statsreply.getLength();
793 if (length < v6statsreply.getLength())
795 v6statsreply.setActionFactory(stat.getActionFactory());
796 v6statsreply.readFrom(data);
797 if (v6statsreply.getLength() < min_len)
799 v6statsreply.setVendorId(vendor);
800 log.trace("V6StatsReply: {}", v6statsreply);
801 length -= v6statsreply.getLength();
802 results.add(v6statsreply);
808 public List<OFStatistics> queryStatistics(Long switchId,
809 OFStatisticsType statType, Object target) {
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
814 if (statType == OFStatisticsType.FLOW) {
815 if (switchSupportsVendorExtStats.get(switchId) == Boolean.TRUE) {
816 statType = OFStatisticsType.VENDOR;
820 List<OFStatistics> list = this.fetchStatisticsFromSwitch(switchId, statType,
823 return (list == null) ? null :
824 (statType == OFStatisticsType.VENDOR) ? v6StatsListToOFStatsList(list) : list;
828 public List<OFStatistics> getOFDescStatistics(Long switchId) {
829 if (!descStatistics.containsKey(switchId))
830 return this.dummyList;
832 return descStatistics.get(switchId);
836 public List<OFStatistics> getOFPortStatistics(Long switchId) {
837 if (!portStatistics.containsKey(switchId)) {
838 return this.dummyList;
841 return portStatistics.get(switchId);
845 public List<OFStatistics> getOFPortStatistics(Long switchId, short portId) {
846 if (!portStatistics.containsKey(switchId)) {
847 return this.dummyList;
849 List<OFStatistics> list = new ArrayList<OFStatistics>(1);
850 for (OFStatistics stats : portStatistics.get(switchId)) {
851 if (((OFPortStatisticsReply) stats).getPortNumber() == portId) {
860 public List<OFStatistics> getOFTableStatistics(Long switchId) {
861 if (!tableStatistics.containsKey(switchId)) {
862 return this.dummyList;
865 return tableStatistics.get(switchId);
869 public List<OFStatistics> getOFTableStatistics(Long switchId, Byte tableId) {
870 if (!tableStatistics.containsKey(switchId)) {
871 return this.dummyList;
874 List<OFStatistics> list = new ArrayList<OFStatistics>(1);
875 for (OFStatistics stats : tableStatistics.get(switchId)) {
876 if (((OFTableStatistics) stats).getTableId() == tableId) {
885 public int getFlowsNumber(long switchId) {
886 return this.flowStatistics.get(switchId).size();
890 * InventoryShim replay for us all the switch addition which happened before
894 public void updateNode(Node node, UpdateType type, Set<Property> props) {
895 Long switchId = (Long) node.getID();
898 addStatisticsTicks(switchId);
901 clearFlowStatsAndTicks(switchId);
907 public void updateNodeConnector(NodeConnector nodeConnector,
908 UpdateType type, Set<Property> props) {
913 * Update the cached port rates for this switch with the latest retrieved
914 * port transmit byte count
918 private synchronized void updatePortsTxRate(long switchId) {
919 List<OFStatistics> newPortStatistics = this.portStatistics.get(switchId);
920 if (newPortStatistics == null) {
923 Map<Short, TxRates> rates = this.txRates.get(switchId);
925 // First time rates for this switch are added
926 rates = new HashMap<Short, TxRates>();
927 txRates.put(switchId, rates);
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);
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);
947 public synchronized long getTransmitRate(Long switchId, Short port) {
949 if (switchId == null || port == null) {
952 Map<Short, TxRates> perSwitch = txRates.get(switchId);
953 if (perSwitch == null) {
956 TxRates portRates = perSwitch.get(port);
957 if (portRates == null) {
960 return portRates.getAverageTxRate();
964 * Manual switch name configuration code
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();
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}$";
981 return (switchId != null && (switchId.matches(regexDatapathID) || switchId
982 .matches(regexDatapathIDLong)));
985 public long getSwitchIDLong(String switchId) {
987 String switchString = "0";
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("-", "");
997 // Handle the 0123456789ABCDEF notation
998 switchString = switchId;
1001 return Long.parseLong(switchString, radix);
1005 * Internal information dump code
1007 private String prettyPrintSwitchMap(ConcurrentMap<Long, StatisticsTicks> map) {
1008 StringBuffer buffer = new StringBuffer();
1010 for (Entry<Long, StatisticsTicks> entry : map.entrySet()) {
1011 buffer.append(HexString.toHexString(entry.getKey()) + "="
1012 + entry.getValue().toString() + " ");
1015 return buffer.toString();
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");
1033 public void _resetSwitchCapability(CommandInterpreter ci) {
1034 String sidString = ci.nextArgument();
1036 if (sidString == null) {
1037 ci.println("Insert the switch id (numeric value)");
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.");
1051 public void _ofbw(CommandInterpreter ci) {
1052 String sidString = ci.nextArgument();
1054 if (sidString == null) {
1055 ci.println("Insert the switch id (numeric value)");
1059 sid = Long.valueOf(sidString);
1060 } catch (NumberFormatException e) {
1061 ci.println("Invalid switch id. Has to be numeric.");
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");
1071 for (Entry<Short, TxRates> entry : thisSwitchRates.entrySet()) {
1072 ci.println("Port: " + entry.getKey() + ": "
1073 + entry.getValue().getAverageTxRate() + " bps");
1079 public void _txratewindow(CommandInterpreter ci) {
1080 String averageWindow = ci.nextArgument();
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");
1089 seconds = Short.valueOf(averageWindow);
1090 } catch (NumberFormatException e) {
1091 ci.println("Invalid period.");
1093 OFStatisticsManager.factoredSamples = (short) (seconds / portTickNumber);
1094 ci.println("New: " + factoredSamples * portTickNumber + " secs");
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();
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");
1110 Short fP, pP, dP, tP;
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());
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.");
1126 statisticsTickNumber = fP;
1127 portTickNumber = pP;
1128 descriptionTickNumber = dP;
1129 tableTickNumber = tP;
1131 ci.println("New Values: fP=" + statisticsTickNumber + "s pP="
1132 + portTickNumber + "s dP=" + descriptionTickNumber + "s tP="
1133 + tableTickNumber + "s");
1137 * This method retrieves user configurations from config.ini and updates
1138 * statisticsTickNumber/portTickNumber/descriptionTickNumber accordingly.
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;
1147 if (fsStr != null) {
1149 fs = Short.parseShort(fsStr);
1151 statisticsTickNumber = fs;
1153 } catch (Exception e) {
1157 if (psStr != null) {
1159 ps = Short.parseShort(psStr);
1161 portTickNumber = ps;
1163 } catch (Exception e) {
1167 if (dsStr != null) {
1169 ds = Short.parseShort(dsStr);
1171 descriptionTickNumber = ds;
1173 } catch (Exception e) {
1177 if (tsStr != null) {
1179 ts = Short.parseShort(tsStr);
1181 tableTickNumber = ts;
1183 } catch (Exception e) {