Upload the contribution of vstf as bottleneck network framework.
[bottlenecks.git] / vstf / vstf / agent / env / basic / collect.py
1 import os
2 import platform
3 import logging
4 from collections import OrderedDict
5
6 from vstf.agent.env.basic.commandline import CommandLine
7 from vstf.common import constants as const
8
9 log = logging.getLogger(__name__)
10 CMD = CommandLine()
11
12
13 class Collect(object):
14     """collect host information such as _cpu, memory and so on"""
15
16     def __init__(self):
17         super(Collect, self).__init__()
18         self._system = self._system()
19         self._cpu = self._cpu()
20
21     def _system(self):
22         """the base _system info
23         {'os info':{'_system':'ubuntu', 'kernel': '3.13.3'}}"""
24         return {const.OS_INFO:
25             {
26                 '_system': open('/etc/issue.net').readline().strip(),
27                 'kernel': platform.uname()[2]
28             }
29         }
30
31     def _memery(self):
32         """ Return the information in /proc/meminfo
33         as a dictionary """
34         meminfo = OrderedDict()
35         with open('/proc/meminfo') as f:
36             for line in f:
37                 meminfo[line.split(':')[0]] = line.split(':')[1].strip()
38
39         return {const.MEMORY_INFO:
40             {
41                 "Mem Total": meminfo['MemTotal'],
42                 "Mem Swap": meminfo['SwapTotal']
43             }
44         }
45
46     def _lscpu(self):
47         ret = {}
48         with os.popen("lscpu") as f:
49             for line in f:
50                 ret[line.split(':')[0].strip()] = line.split(':')[1].strip()
51         return ret
52
53     def _cpu(self):
54         ret = []
55         with open('/proc/cpuinfo') as f:
56             cpuinfo = OrderedDict()
57             for line in f:
58                 if not line.strip():
59                     ret.append(cpuinfo)
60                     cpuinfo = OrderedDict()
61                 elif len(line.split(':')) == 2:
62                     cpuinfo[line.split(':')[0].strip()] = line.split(':')[1].strip()
63                 else:
64                     log.error("_cpu info unknow format <%(c)s>", {'c': line})
65         return {const.CPU_INFO:
66             dict(
67                 {
68                     "Model Name": ret[0]['model name'],
69                     "Address sizes": ret[0]['address sizes']
70                 },
71                 **(self._lscpu())
72             )
73         }
74
75     def _hw_sysinfo(self):
76         cmdline = "dmidecode | grep  -A 2 'System Information' | grep -v 'System Information'"
77         ret, output = CMD.execute(cmdline, shell=True)
78         if ret:
79             result = {}
80             # del the stderr
81             for tmp in output.strip().split('\n'):
82                 if tmp is None or tmp is "":
83                     continue
84                 # split the items 
85                 tmp = tmp.split(":")
86                 if len(tmp) >= 2:
87                     # first item as key, and the other as value
88                     result[tmp[0].strip("\t")] = ";".join(tmp[1:])
89             return {const.HW_INFO: result}
90         else:
91             return {const.HW_INFO: "get hw info failed. check the host by cmd: dmidecode"}
92
93     def collect_host_info(self):
94         return [self._system, self._cpu, self._memery(), self._hw_sysinfo()]
95
96
97 if __name__ == "__main__":
98     c = Collect()
99     import json
100
101     print json.dumps(c.collect_host_info(), indent=4)