1 ##############################################################################
2 # Copyright (c) 2015 Huawei Technologies Co.,Ltd and others.
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
13 from signal import SIGINT
16 from vstf.common.utils import check_call, my_popen, kill_by_name
18 LOG = logging.getLogger(__name__)
23 self.netns_exec_str = "ip netns exec %s "
24 self.vnstat_cmd_str = "vnstat -l -i %s"
25 self.child_process = {}
27 def run_vnstat(self, device, namespace=None):
28 cmd = self.vnstat_cmd_str
30 cmd1 = (self.netns_exec_str + "ifconfig %s") % (namespace, device)
31 check_call(cmd1, shell=True)
32 cmd = self.netns_exec_str + cmd
33 cmd = cmd % (namespace, device)
36 check_call("which vnstat", shell=True)
37 child = my_popen(cmd.split(), stdout=subprocess.PIPE)
38 self.child_process[child.pid] = child
41 def kill_vnstat(self, pid, namespace=None):
42 assert pid in self.child_process
44 process = self.child_process.pop(pid)
45 out = process.stdout.read()
47 LOG.info("os.kill(pid = %s)", pid)
48 data = {'tool': 'vnstat', 'type': 'nic', 'raw_data': out}
52 for _, process in self.child_process.items():
55 LOG.info("process.kill(vnstat:%s)", process.pid)
56 self.child_process = {}
59 def process(self, raw):
60 buf = raw.splitlines()
65 digits = re.compile(r"\d+\.?\d*")
66 units = re.compile("(?:gib|mib|kib|kbit/s|gbits/s|mbit/s|p/s)", re.IGNORECASE | re.MULTILINE)
67 units_arr = units.findall(buf)
71 digits_arr = digits.findall(buf)
73 for i in range(len(digits_arr)):
74 digits_arr[i] = round(float(digits_arr[i]), 2)
76 m['rxpck'], m['txpck'] = digits_arr[8], digits_arr[9]
77 m['time'] = digits_arr[-1]
78 digits_arr = digits_arr[:8] + digits_arr[10:-1]
80 for unit in units_arr:
83 digits_arr[index] *= 1024
85 digits_arr[index] /= 1024
86 elif unit == 'gbit/s':
87 digits_arr[index] *= 1000
88 elif unit == 'kbit/s':
89 digits_arr[index] /= 1000
94 for i in range(len(digits_arr)):
95 digits_arr[i] = round(digits_arr[i], 2)
97 m['rxmB'], m['txmB'] = digits_arr[0:2]
98 m['rxmB_max/s'], m['txmB_max/s'] = digits_arr[2:4]
99 m['rxmB/s'], m['txmB/s'] = digits_arr[4:6]
100 m['rxmB_min/s'], m['txmB_min/s'] = digits_arr[6:8]
101 m['rxpck_max/s'], m['txpck_max/s'] = digits_arr[8:10]
102 m['rxpck/s'], m['txpck/s'] = digits_arr[10:12]
103 m['rxpck_min/s'], m['txpck_min/s'] = digits_arr[12:14]
106 def force_clean(self):
107 LOG.info("%s %s start", self.__class__, self.force_clean.__name__)
108 kill_by_name("vnstat")
109 self.child_process = {}