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__)
24 self.netns_exec_str = "ip netns exec %s "
25 self.vnstat_cmd_str = "vnstat -l -i %s"
26 self.child_process = {}
28 def run_vnstat(self, device, namespace=None):
29 cmd = self.vnstat_cmd_str
31 cmd1 = (self.netns_exec_str + "ifconfig %s") % (namespace, device)
32 check_call(cmd1, shell=True)
33 cmd = self.netns_exec_str + cmd
34 cmd = cmd % (namespace, device)
37 check_call("which vnstat", shell=True)
38 child = my_popen(cmd.split(), stdout=subprocess.PIPE)
39 self.child_process[child.pid] = child
42 def kill_vnstat(self, pid, namespace=None):
43 assert pid in self.child_process
45 process = self.child_process.pop(pid)
46 out = process.stdout.read()
48 LOG.info("os.kill(pid = %s)", pid)
49 data = {'tool': 'vnstat', 'type': 'nic', 'raw_data': out}
53 for _, process in self.child_process.items():
56 LOG.info("process.kill(vnstat:%s)", process.pid)
57 self.child_process = {}
60 def process(self, raw):
61 buf = raw.splitlines()
66 digits = re.compile(r"\d+\.?\d*")
68 "(?:gib|mib|kib|kbit/s|gbits/s|mbit/s|p/s)",
69 re.IGNORECASE | re.MULTILINE)
70 units_arr = units.findall(buf)
74 digits_arr = digits.findall(buf)
76 for i in range(len(digits_arr)):
77 digits_arr[i] = round(float(digits_arr[i]), 2)
79 m['rxpck'], m['txpck'] = digits_arr[8], digits_arr[9]
80 m['time'] = digits_arr[-1]
81 digits_arr = digits_arr[:8] + digits_arr[10:-1]
83 for unit in units_arr:
86 digits_arr[index] *= 1024
88 digits_arr[index] /= 1024
89 elif unit == 'gbit/s':
90 digits_arr[index] *= 1000
91 elif unit == 'kbit/s':
92 digits_arr[index] /= 1000
97 for i in range(len(digits_arr)):
98 digits_arr[i] = round(digits_arr[i], 2)
100 m['rxmB'], m['txmB'] = digits_arr[0:2]
101 m['rxmB_max/s'], m['txmB_max/s'] = digits_arr[2:4]
102 m['rxmB/s'], m['txmB/s'] = digits_arr[4:6]
103 m['rxmB_min/s'], m['txmB_min/s'] = digits_arr[6:8]
104 m['rxpck_max/s'], m['txpck_max/s'] = digits_arr[8:10]
105 m['rxpck/s'], m['txpck/s'] = digits_arr[10:12]
106 m['rxpck_min/s'], m['txpck_min/s'] = digits_arr[12:14]
109 def force_clean(self):
110 LOG.info("%s %s start", self.__class__, self.force_clean.__name__)
111 kill_by_name("vnstat")
112 self.child_process = {}