From 4e6d48b7afd27d57d791de1388d115e4ced32981 Mon Sep 17 00:00:00 2001 From: dave Date: Sun, 1 Oct 2017 14:35:50 -0700 Subject: [PATCH] add network stats module --- pymonitor/__init__.py | 2 +- pymonitor/monitors/ifstats.py | 85 +++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 pymonitor/monitors/ifstats.py diff --git a/pymonitor/__init__.py b/pymonitor/__init__.py index 3dc1f76..485f44a 100644 --- a/pymonitor/__init__.py +++ b/pymonitor/__init__.py @@ -1 +1 @@ -__version__ = "0.1.0" +__version__ = "0.1.1" diff --git a/pymonitor/monitors/ifstats.py b/pymonitor/monitors/ifstats.py new file mode 100644 index 0000000..8d8e7f8 --- /dev/null +++ b/pymonitor/monitors/ifstats.py @@ -0,0 +1,85 @@ +from collections import defaultdict +from time import time + + +rx_bytes, rx_packets, rx_errs, rx_drop, rx_fifo, rx_frame, rx_compressed, rx_multicast, \ + tx_bytes, tx_packets, tx_errs, tx_drop, tx_fifo, tx_colls, tx_carrier, tx_compressed = range(16) + + +previous = defaultdict(lambda: [-1 for i in range(17)]) + + +def ifstats(): + with open("/proc/net/dev", "r") as f: + _, _ = f.readline(), f.readline() + + for line in f.readlines(): + fields = line.split() + ifname = fields.pop(0).rstrip(":") + for i in range(0, len(fields)): + fields[i] = int(fields[i]) + + record = {"iface": ifname, + "rx_bytes": fields[rx_bytes], + "tx_bytes": fields[tx_bytes], + "rx_packets": fields[rx_packets], + "tx_packets": fields[tx_packets], + } + + prev = previous[ifname] + if prev[rx_bytes] != -1: + tdelta = time() - prev[-1] + record["rx_traffic"] = round((fields[rx_bytes] - prev[rx_bytes]) / tdelta) + record["tx_traffic"] = round((fields[tx_bytes] - prev[tx_bytes]) / tdelta) + record["tx_packetcnt"] = round((fields[tx_packets] - prev[tx_packets]) / tdelta) + record["rx_packetcnt"] = round((fields[rx_packets] - prev[rx_packets]) / tdelta) + + previous[ifname] = fields + [time()] + + yield record + + +mapping = { + "load": { + "properties": { + "iface": { + "type": "string", + "index": "not_analyzed" + }, + "rx_bytes": { + "type": "long" + }, + "tx_bytes": { + "type": "long" + }, + "rx_packets": { + "type": "long" + }, + "tx_packets": { + "type": "long" + }, + "rx_traffic": { + "type": "long" + }, + "tx_traffic": { + "type": "long" + }, + "tx_packetcnt": { + "type": "long" + }, + "rx_packetcnt": { + "type": "long" + } + } + } +} + + +if __name__ == '__main__': + from time import sleep + for item in ifstats(): + print(item) + print("-") + sleep(2) + for item in ifstats(): + print(item)