Merge "Change PTL informatin in INFO"
[bottlenecks.git] / testsuites / vstf / vstf_scripts / 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(':')[
72                         1].strip()
73                 else:
74                     log.error("_cpu info unknow format <%(c)s>", {'c': line})
75         return {const.CPU_INFO:
76                 dict(
77                     {
78                         "Model Name": ret[0]['model name'],
79                         "Address sizes": ret[0]['address sizes']
80                     },
81                     **(self._lscpu())
82                 )
83                 }
84
85     def _hw_sysinfo(self):
86         cmdline = "dmidecode | grep  -A 2 'System Information' | grep -v 'System Information'"
87         ret, output = CMD.execute(cmdline, shell=True)
88         if ret:
89             result = {}
90             # del the stderr
91             for tmp in output.strip().split('\n'):
92                 if tmp is None or tmp is "":
93                     continue
94                 # split the items
95                 tmp = tmp.split(":")
96                 if len(tmp) >= 2:
97                     # first item as key, and the other as value
98                     result[tmp[0].strip("\t")] = ";".join(tmp[1:])
99             return {const.HW_INFO: result}
100         else:
101             return {
102                 const.HW_INFO: "get hw info failed. check the host by cmd: dmidecode"}
103
104     def collect_host_info(self):
105         return [self._system, self._cpu, self._memery(), self._hw_sysinfo()]
106
107
108 if __name__ == "__main__":
109     c = Collect()
110     import json
111
112     print json.dumps(c.collect_host_info(), indent=4)