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__)
25 self.sar_cmd_str = "sar -u %(interval)s"
26 self.child_process = {}
28 def start(self, interval=2):
29 cmd = self.sar_cmd_str % {'interval': interval}
32 stdout=subprocess.PIPE,
33 stderr=subprocess.PIPE)
35 if child.poll() is not None:
37 raise Exception("start vnstat error, vnstat is not running")
38 self.child_process[child.pid] = child
42 assert pid in self.child_process
44 process = self.child_process.pop(pid)
45 out = process.stdout.read()
47 data = {'raw_data': out, 'tool': 'sar', 'type': 'cpu'}
48 cpu_info = collect.Collect().collect_host_info()[1]
49 cpu_num = cpu_info['CPU INFO']['CPU(s)']
50 cpu_mhz = cpu_info['CPU INFO']['CPU MHz']
51 data.update({'cpu_num': float(cpu_num), 'cpu_mhz': float(cpu_mhz)})
54 def process(self, raw):
55 lines = raw.splitlines()
57 head = lines[2].split()[3:]
58 average = lines[-1].split()[2:]
60 for h, d in zip(head, average):
61 data[h.strip('%')] = float(d)
62 cpu_num = check_output(
63 'cat /proc/cpuinfo | grep processor | wc -l',
65 data.update({'cpu_num': int(cpu_num)})
69 for _, process in self.child_process.items():
72 self.child_process = {}
75 def force_clean(self):
76 LOG.info("%s %s start", self.__class__, self.force_clean.__name__)
78 self.child_process = {}
81 if __name__ == '__main__':
82 logging.basicConfig(level=logging.DEBUG)
88 print q.process(raw['raw_data'])