10 from signal import SIGINT
12 from vstf.common.utils import check_output, my_popen, kill_by_name
13 from vstf.agent.env.basic import collect
15 LOG = logging.getLogger(__name__)
20 self.sar_cmd_str = "sar -u %(interval)s"
21 self.child_process = {}
23 def start(self, interval=2):
24 cmd = self.sar_cmd_str % {'interval': interval}
25 child = my_popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
27 if child.poll() is not None:
29 raise Exception("start vnstat error, vnstat is not running")
30 self.child_process[child.pid] = child
34 assert pid in self.child_process
36 process = self.child_process.pop(pid)
37 out = process.stdout.read()
39 data = {'raw_data': out, 'tool': 'sar', 'type': 'cpu'}
40 cpu_info = collect.Collect().collect_host_info()[1]
41 cpu_num = cpu_info['CPU INFO']['CPU(s)']
42 cpu_mhz = cpu_info['CPU INFO']['CPU MHz']
43 data.update({'cpu_num': float(cpu_num), 'cpu_mhz': float(cpu_mhz)})
46 def process(self, raw):
47 lines = raw.splitlines()
49 head = lines[2].split()[3:]
50 average = lines[-1].split()[2:]
52 for h, d in zip(head, average):
53 data[h.strip('%')] = float(d)
54 cpu_num = check_output('cat /proc/cpuinfo | grep processor | wc -l', shell=True).strip()
55 data.update({'cpu_num': int(cpu_num)})
59 for _, process in self.child_process.items():
62 self.child_process = {}
65 def force_clean(self):
66 LOG.info("%s %s start", self.__class__, self.force_clean.__name__)
68 self.child_process = {}
71 if __name__ == '__main__':
72 logging.basicConfig(level=logging.DEBUG)
78 print q.process(raw['raw_data'])