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