9 from signal import SIGINT
12 from vstf.common.utils import check_call, my_popen, kill_by_name
14 LOG = logging.getLogger(__name__)
19 self.netns_exec_str = "ip netns exec %s "
20 self.vnstat_cmd_str = "vnstat -l -i %s"
21 self.child_process = {}
23 def run_vnstat(self, device, namespace=None):
24 cmd = self.vnstat_cmd_str
26 cmd1 = (self.netns_exec_str + "ifconfig %s") % (namespace, device)
27 check_call(cmd1, shell=True)
28 cmd = self.netns_exec_str + cmd
29 cmd = cmd % (namespace, device)
32 check_call("which vnstat", shell=True)
33 child = my_popen(cmd.split(), stdout=subprocess.PIPE)
34 self.child_process[child.pid] = child
37 def kill_vnstat(self, pid, namespace=None):
38 assert pid in self.child_process
40 process = self.child_process.pop(pid)
41 out = process.stdout.read()
43 LOG.info("os.kill(pid = %s)", pid)
44 data = {'tool': 'vnstat', 'type': 'nic', 'raw_data': out}
48 for _, process in self.child_process.items():
51 LOG.info("process.kill(vnstat:%s)", process.pid)
52 self.child_process = {}
55 def process(self, raw):
56 buf = raw.splitlines()
61 digits = re.compile(r"\d+\.?\d*")
62 units = re.compile("(?:gib|mib|kib|kbit/s|gbits/s|mbit/s|p/s)", re.IGNORECASE | re.MULTILINE)
63 units_arr = units.findall(buf)
67 digits_arr = digits.findall(buf)
69 for i in range(len(digits_arr)):
70 digits_arr[i] = round(float(digits_arr[i]), 2)
72 m['rxpck'], m['txpck'] = digits_arr[8], digits_arr[9]
73 m['time'] = digits_arr[-1]
74 digits_arr = digits_arr[:8] + digits_arr[10:-1]
76 for unit in units_arr:
79 digits_arr[index] *= 1024
81 digits_arr[index] /= 1024
82 elif unit == 'gbit/s':
83 digits_arr[index] *= 1000
84 elif unit == 'kbit/s':
85 digits_arr[index] /= 1000
90 for i in range(len(digits_arr)):
91 digits_arr[i] = round(digits_arr[i], 2)
93 m['rxmB'], m['txmB'] = digits_arr[0:2]
94 m['rxmB_max/s'], m['txmB_max/s'] = digits_arr[2:4]
95 m['rxmB/s'], m['txmB/s'] = digits_arr[4:6]
96 m['rxmB_min/s'], m['txmB_min/s'] = digits_arr[6:8]
97 m['rxpck_max/s'], m['txpck_max/s'] = digits_arr[8:10]
98 m['rxpck/s'], m['txpck/s'] = digits_arr[10:12]
99 m['rxpck_min/s'], m['txpck_min/s'] = digits_arr[12:14]
102 def force_clean(self):
103 LOG.info("%s %s start", self.__class__, self.force_clean.__name__)
104 kill_by_name("vnstat")
105 self.child_process = {}