Upload the contribution of vstf as bottleneck network framework.
[bottlenecks.git] / vstf / vstf / agent / perf / sar.py
1 """
2 Created on 2015-8-6
3
4 @author: y00228926
5 """
6 import subprocess
7 import logging
8 import time
9 import os
10 from signal import SIGINT
11
12 from vstf.common.utils import check_output, my_popen, kill_by_name
13 from vstf.agent.env.basic import collect
14
15 LOG = logging.getLogger(__name__)
16
17
18 class Sar(object):
19     def __init__(self):
20         self.sar_cmd_str = "sar -u %(interval)s"
21         self.child_process = {}
22
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)
26         time.sleep(1)
27         if child.poll() is not None:
28             print child.poll()
29             raise Exception("start vnstat error, vnstat is not running")
30         self.child_process[child.pid] = child
31         return child.pid
32
33     def stop(self, pid):
34         assert pid in self.child_process
35         os.kill(pid, SIGINT)
36         process = self.child_process.pop(pid)
37         out = process.stdout.read()
38         process.wait()
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)})
44         return data
45
46     def process(self, raw):
47         lines = raw.splitlines()
48         # print lines
49         head = lines[2].split()[3:]
50         average = lines[-1].split()[2:]
51         data = {}
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)})
56         return data
57
58     def clean(self):
59         for _, process in self.child_process.items():
60             process.kill()
61             process.wait()
62         self.child_process = {}
63         return True
64
65     def force_clean(self):
66         LOG.info("%s %s start", self.__class__, self.force_clean.__name__)
67         kill_by_name("sar")
68         self.child_process = {}
69         return True
70
71 if __name__ == '__main__':
72     logging.basicConfig(level=logging.DEBUG)
73     q = Sar()
74     pid = q.start()
75     time.sleep(10)
76     raw = q.stop(pid)
77     print raw
78     print q.process(raw['raw_data'])