Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add DUT resources monitoring feature. #1121

Merged
merged 5 commits into from
Oct 8, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
from ansible_host import AnsibleHost
from loganalyzer import LogAnalyzer

pytest_plugins = ('ptf_fixtures', 'ansible_fixtures')

pytest_plugins = ('ptf_fixtures', 'ansible_fixtures', 'plugins.dut_monitor.pytest_dut_monitor')

# Add the tests folder to sys.path, for importing the lib package
_current_file_dir = os.path.dirname(os.path.realpath(__file__))
Expand Down Expand Up @@ -139,3 +140,9 @@ def loganalyzer(duthost, request):
# Add end marker into DUT syslog
loganalyzer._add_end_marker(marker)

@pytest.fixture(scope="session")
def creds():
""" read and yield eos configuration """
with open("../ansible/group_vars/lab/secrets.yml") as stream:
creds = yaml.safe_load(stream)
return creds
Empty file added tests/plugins/__init__.py
Empty file.
Empty file.
89 changes: 89 additions & 0 deletions tests/plugins/dut_monitor/dut_monitor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import argparse
import time
import os

from datetime import datetime


FETCH_CPU_CMD = "ps -eo pcpu,args | sort -k 1 -r | tail -n +2"
FETCH_HDD_CMD = "df -hm /"
MEASURE_DELAY = 2


def process_cpu(log_file):
"""
@summary: Fetch CPU utilization. Write to the file total and top 10 process CPU utilization.
@param log_file: Opened file object to store fetched CPU utilization.
"""
buff = []
general_template = """
"{timestamp}":
total: {total}
top_consumer:
yvolynets-mlnx marked this conversation as resolved.
Show resolved Hide resolved
"""
per_process_template = " {cpu_utilization}: \"{process}\""
top_consumer_list = []
total = 0
top_consumer_counter = 10

for line in os.popen(FETCH_CPU_CMD).readlines():
process_consumed = float(line.split()[0])
total += process_consumed
if top_consumer_counter:
yvolynets-mlnx marked this conversation as resolved.
Show resolved Hide resolved
top_consumer_list.append(per_process_template.format(cpu_utilization=process_consumed, process=line.split()[1]))
yvolynets-mlnx marked this conversation as resolved.
Show resolved Hide resolved
top_consumer_counter -= 1

result = general_template.format(timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), total=total) + "\n".join(top_consumer_list)
yvolynets-mlnx marked this conversation as resolved.
Show resolved Hide resolved
log_file.write(result)


def process_ram(log_file):
"""
@summary: Fetch RAM utilization and write it to the file. Use 'MemTotal' and 'MemAvailable' from '/proc/meminfo' to obtain used RAM amount.
@param log_file: Opened file object to store fetched CPU utilization.
yvolynets-mlnx marked this conversation as resolved.
Show resolved Hide resolved
"""
with open('/proc/meminfo') as stream:
for line in stream:
if 'MemAvailable' in line:
available_mem_in_kb = int(line.split()[1])
if 'MemTotal' in line:
total_mem_in_kb = int(line.split()[1])

used = total_mem_in_kb - available_mem_in_kb
used_percent = used * 100 / total_mem_in_kb
log_file.write("\"{date}\": {used_ram}\n".format(date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), used_ram=used_percent))


def process_hdd(log_file):
"""
@summary: Fetch used amount of HDD and write it to the file. Execute command defined in FETCH_HDD_CMD.
yvolynets-mlnx marked this conversation as resolved.
Show resolved Hide resolved
@param log_file: Opened file object to store fetched CPU utilization.
yvolynets-mlnx marked this conversation as resolved.
Show resolved Hide resolved
"""
output_line_id = 1
use_value_id = 4
hdd_usage = os.popen(FETCH_HDD_CMD).read().split("\n")[output_line_id].split()[use_value_id].rstrip("%")
log_file.write("\"{date}\": {used_ram}\n".format(date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), used_ram=hdd_usage))


def main():
cpu_log = open("/tmp/cpu.log", "w")
ram_log = open("/tmp/ram.log", "w")
hdd_log = open("/tmp/hdd.log", "w")

print "Started resources monitoring ..."
while True:
process_cpu(cpu_log)
process_ram(ram_log)
process_hdd(hdd_log)
time.sleep(MEASURE_DELAY)
cpu_log.flush()
ram_log.flush()
hdd_log.flush()

if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--start", help="device file", action="store_true", default=False)
args = parser.parse_args()

if args.start:
main()
18 changes: 18 additions & 0 deletions tests/plugins/dut_monitor/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import pprint

class HDDThresholdExceeded(Exception):
"""Raised when HDD consumption on DUT exceed threshold"""
def __repr__(self):
return pprint.pformat(self.message)


class RAMThresholdExceeded(Exception):
"""Raised when RAM consumption on DUT exceed threshold"""
def __repr__(self):
return pprint.pformat(self.message)


class CPUThresholdExceeded(Exception):
"""Raised when CPU consumption on DUT exceed threshold"""
def __repr__(self):
return pprint.pformat(self.message)
Loading