ONOS-1440: Implements port statistics feature, which polls port statistics of all devices every 10 seconds. Also, implemented a simple portstats ONOS CLI command to show the statistics.

Change-Id: I57e046ae2c2463a58b478d3a5b523422cde71ba2
diff --git a/providers/openflow/device/src/main/java/org/onosproject/provider/of/device/impl/OpenFlowDeviceProvider.java b/providers/openflow/device/src/main/java/org/onosproject/provider/of/device/impl/OpenFlowDeviceProvider.java
index 504d047..d23817f 100644
--- a/providers/openflow/device/src/main/java/org/onosproject/provider/of/device/impl/OpenFlowDeviceProvider.java
+++ b/providers/openflow/device/src/main/java/org/onosproject/provider/of/device/impl/OpenFlowDeviceProvider.java
@@ -15,6 +15,8 @@
  */
 package org.onosproject.provider.of.device.impl;
 
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
 import org.apache.felix.scr.annotations.Activate;
 import org.apache.felix.scr.annotations.Component;
 import org.apache.felix.scr.annotations.Deactivate;
@@ -29,31 +31,43 @@
 import org.onosproject.net.SparseAnnotations;
 import org.onosproject.net.device.DefaultDeviceDescription;
 import org.onosproject.net.device.DefaultPortDescription;
+import org.onosproject.net.device.DefaultPortStatistics;
 import org.onosproject.net.device.DeviceDescription;
 import org.onosproject.net.device.DeviceProvider;
 import org.onosproject.net.device.DeviceProviderRegistry;
 import org.onosproject.net.device.DeviceProviderService;
 import org.onosproject.net.device.PortDescription;
+import org.onosproject.net.device.PortStatistics;
 import org.onosproject.net.provider.AbstractProvider;
 import org.onosproject.net.provider.ProviderId;
 import org.onosproject.openflow.controller.Dpid;
 import org.onosproject.openflow.controller.OpenFlowController;
+import org.onosproject.openflow.controller.OpenFlowEventListener;
 import org.onosproject.openflow.controller.OpenFlowSwitch;
 import org.onosproject.openflow.controller.OpenFlowSwitchListener;
 import org.onosproject.openflow.controller.RoleState;
 import org.onlab.packet.ChassisId;
 import org.projectfloodlight.openflow.protocol.OFFactory;
+import org.projectfloodlight.openflow.protocol.OFMessage;
 import org.projectfloodlight.openflow.protocol.OFPortConfig;
 import org.projectfloodlight.openflow.protocol.OFPortDesc;
 import org.projectfloodlight.openflow.protocol.OFPortFeatures;
 import org.projectfloodlight.openflow.protocol.OFPortReason;
 import org.projectfloodlight.openflow.protocol.OFPortState;
+import org.projectfloodlight.openflow.protocol.OFPortStatsEntry;
+import org.projectfloodlight.openflow.protocol.OFPortStatsReply;
 import org.projectfloodlight.openflow.protocol.OFPortStatus;
+import org.projectfloodlight.openflow.protocol.OFStatsReply;
+import org.projectfloodlight.openflow.protocol.OFStatsType;
 import org.projectfloodlight.openflow.protocol.OFVersion;
 import org.projectfloodlight.openflow.types.PortSpeed;
 import org.slf4j.Logger;
 
 import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 
 import com.google.common.base.Strings;
@@ -83,7 +97,12 @@
 
     private DeviceProviderService providerService;
 
-    private final OpenFlowSwitchListener listener = new InternalDeviceProvider();
+    private final InternalDeviceProvider listener = new InternalDeviceProvider();
+
+    // TODO: We need to make the poll interval configurable.
+    static final int POLL_INTERVAL = 10;
+
+    private HashMap<Dpid, PortStatsCollector> collectors = Maps.newHashMap();
 
     /**
      * Creates an OpenFlow device provider.
@@ -96,6 +115,7 @@
     public void activate() {
         providerService = providerRegistry.register(this);
         controller.addListener(listener);
+        controller.addEventListener(listener);
         for (OpenFlowSwitch sw : controller.getSwitches()) {
             try {
                 listener.switchAdded(new Dpid(sw.getId()));
@@ -105,6 +125,9 @@
                 // disconnect to trigger switch-add later
                 sw.disconnectSwitch();
             }
+            PortStatsCollector psc = new PortStatsCollector(sw, POLL_INTERVAL);
+            psc.start();
+            collectors.put(new Dpid(sw.getId()), psc);
         }
         LOG.info("Started");
     }
@@ -174,7 +197,45 @@
         LOG.info("Accepting mastership role change for device {}", deviceId);
     }
 
-    private class InternalDeviceProvider implements OpenFlowSwitchListener {
+    private void pushPortMetrics(Dpid dpid, OFPortStatsReply msg) {
+        DeviceId deviceId = DeviceId.deviceId(dpid.uri(dpid));
+
+        Collection<PortStatistics> stats = buildPortStatistics(deviceId, msg);
+
+        providerService.updatePortStatistics(deviceId, stats);
+    }
+
+    private Collection<PortStatistics> buildPortStatistics(DeviceId deviceId, OFPortStatsReply msg) {
+
+        HashSet<PortStatistics> stats = Sets.newHashSet();
+
+        for (OFPortStatsEntry entry: msg.getEntries()) {
+            if (entry.getPortNo().getPortNumber() < 0) {
+                continue;
+            }
+            DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
+            DefaultPortStatistics stat = builder.setDeviceId(deviceId)
+                    .setPort(entry.getPortNo().getPortNumber())
+                    .setPacketsReceived(entry.getRxPackets().getValue())
+                    .setPacketsSent(entry.getTxPackets().getValue())
+                    .setBytesReceived(entry.getRxBytes().getValue())
+                    .setBytesSent(entry.getTxBytes().getValue())
+                    .setPacketsRxDropped(entry.getRxDropped().getValue())
+                    .setPacketsTxDropped(entry.getTxDropped().getValue())
+                    .setPacketsRxErrors(entry.getRxErrors().getValue())
+                    .setPacketsTxErrors(entry.getTxErrors().getValue())
+                    .setDurationSec(entry.getDurationSec())
+                    .setDurationNano(entry.getDurationNsec())
+                    .build();
+
+            stats.add(stat);
+        }
+
+        return Collections.unmodifiableSet(stats);
+
+    }
+
+    private class InternalDeviceProvider implements OpenFlowSwitchListener, OpenFlowEventListener {
         @Override
         public void switchAdded(Dpid dpid) {
             if (providerService == null) {
@@ -201,6 +262,11 @@
                                                  cId, annotations);
             providerService.deviceConnected(did, description);
             providerService.updatePorts(did, buildPortDescriptions(sw.getPorts()));
+
+            PortStatsCollector psc = new PortStatsCollector(
+                        controller.getSwitch(dpid), POLL_INTERVAL);
+            psc.start();
+            collectors.put(dpid, psc);
         }
 
         @Override
@@ -209,8 +275,12 @@
                 return;
             }
             providerService.deviceDisconnected(deviceId(uri(dpid)));
-        }
 
+            PortStatsCollector collector = collectors.remove(dpid);
+            if (collector != null) {
+                collector.stop();
+            }
+        }
 
         @Override
         public void switchChanged(Dpid dpid) {
@@ -328,6 +398,19 @@
             }
             return portSpeed.getSpeedBps() / MBPS;
         }
+
+        @Override
+        public void handleMessage(Dpid dpid, OFMessage msg) {
+            switch (msg.getType()) {
+                case STATS_REPLY:
+                    if (((OFStatsReply) msg).getStatsType() == OFStatsType.PORT) {
+                        pushPortMetrics(dpid, (OFPortStatsReply) msg);
+                    }
+                    break;
+                default:
+                    break;
+            }
+        }
     }
 
 }
diff --git a/providers/openflow/device/src/main/java/org/onosproject/provider/of/device/impl/PortStatsCollector.java b/providers/openflow/device/src/main/java/org/onosproject/provider/of/device/impl/PortStatsCollector.java
new file mode 100644
index 0000000..36d7948
--- /dev/null
+++ b/providers/openflow/device/src/main/java/org/onosproject/provider/of/device/impl/PortStatsCollector.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2015 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.provider.of.device.impl;
+
+import org.jboss.netty.util.HashedWheelTimer;
+import org.jboss.netty.util.Timeout;
+import org.jboss.netty.util.TimerTask;
+import org.onlab.util.Timer;
+import org.onosproject.openflow.controller.OpenFlowSwitch;
+import org.onosproject.openflow.controller.RoleState;
+import org.projectfloodlight.openflow.protocol.OFPortStatsRequest;
+import org.projectfloodlight.openflow.types.OFPort;
+import org.slf4j.Logger;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+/*
+ * Sends Group Stats Request and collect the group statistics with a time interval.
+ */
+public class PortStatsCollector implements TimerTask {
+
+    // TODO: Refactoring is required using ScheduledExecutorService
+
+    private final HashedWheelTimer timer = Timer.getTimer();
+    private final OpenFlowSwitch sw;
+    private final Logger log = getLogger(getClass());
+    private final int refreshInterval;
+    private final AtomicLong xidAtomic = new AtomicLong(1);
+
+    private Timeout timeout;
+
+    private boolean stopTimer = false;
+
+    /**
+     * Creates a GroupStatsCollector object.
+     *
+     * @param sw Open Flow switch
+     * @param interval time interval for collecting group statistic
+     */
+    public PortStatsCollector(OpenFlowSwitch sw, int interval) {
+        this.sw = sw;
+        this.refreshInterval = interval;
+    }
+
+    @Override
+    public void run(Timeout timeout) throws Exception {
+        log.trace("Collecting stats for {}", sw.getStringId());
+
+        sendPortStatistic();
+
+        if (!this.stopTimer) {
+            log.trace("Scheduling stats collection in {} seconds for {}",
+                    this.refreshInterval, this.sw.getStringId());
+            timeout.getTimer().newTimeout(this, refreshInterval,
+                    TimeUnit.SECONDS);
+        }
+    }
+
+    private void sendPortStatistic() {
+        if (log.isTraceEnabled()) {
+            log.trace("sendGroupStatistics {}:{}", sw.getStringId(), sw.getRole());
+        }
+        if (sw.getRole() != RoleState.MASTER) {
+            return;
+        }
+        Long statsXid = xidAtomic.getAndIncrement();
+        OFPortStatsRequest statsRequest = sw.factory().buildPortStatsRequest()
+                .setPortNo(OFPort.ANY)
+                .setXid(statsXid)
+                .build();
+        sw.sendMsg(statsRequest);
+    }
+
+    /**
+     * Starts the collector.
+     */
+    public void start() {
+        log.info("Starting Port Stats collection thread for {}", sw.getStringId());
+        timeout = timer.newTimeout(this, 1, TimeUnit.SECONDS);
+    }
+
+    /**
+     * Stops the collector.
+     */
+    public void stop() {
+        log.info("Stopping Port Stats collection thread for {}", sw.getStringId());
+        this.stopTimer = true;
+        timeout.cancel();
+    }
+}