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 ##############################################################################
14 from signal import SIGINT
16 from vstf.common.utils import check_output, my_popen, kill_by_name
17 from vstf.agent.env.basic import collect
19 LOG = logging.getLogger(__name__)
24 self.sar_cmd_str = "sar -u %(interval)s"
25 self.child_process = {}
27 def start(self, interval=2):
28 cmd = self.sar_cmd_str % {'interval': interval}
29 child = my_popen(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
31 if child.poll() is not None:
33 raise Exception("start vnstat error, vnstat is not running")
34 self.child_process[child.pid] = child
38 assert pid in self.child_process
40 process = self.child_process.pop(pid)
41 out = process.stdout.read()
43 data = {'raw_data': out, 'tool': 'sar', 'type': 'cpu'}
44 cpu_info = collect.Collect().collect_host_info()[1]
45 cpu_num = cpu_info['CPU INFO']['CPU(s)']
46 cpu_mhz = cpu_info['CPU INFO']['CPU MHz']
47 data.update({'cpu_num': float(cpu_num), 'cpu_mhz': float(cpu_mhz)})
50 def process(self, raw):
51 lines = raw.splitlines()
53 head = lines[2].split()[3:]
54 average = lines[-1].split()[2:]
56 for h, d in zip(head, average):
57 data[h.strip('%')] = float(d)
58 cpu_num = check_output('cat /proc/cpuinfo | grep processor | wc -l', shell=True).strip()
59 data.update({'cpu_num': int(cpu_num)})
63 for _, process in self.child_process.items():
66 self.child_process = {}
69 def force_clean(self):
70 LOG.info("%s %s start", self.__class__, self.force_clean.__name__)
72 self.child_process = {}
75 if __name__ == '__main__':
76 logging.basicConfig(level=logging.DEBUG)
82 print q.process(raw['raw_data'])