1 # Copyright 2015-2016 Intel Corporation.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 """Tools for access to OS details
23 from conf import settings as S
25 def match_line(file_name, pattern):
26 """ loops through given file and returns first line matching given pattern
28 :returns: string with the matching line without end of line or None
31 with open(file_name, encoding="latin-1") as file_:
35 if not line.strip().startswith(pattern):
38 return line.strip().rstrip('\n')
46 :returns: Return distro name as a string
48 return ' '.join(platform.dist())
51 """Get kernel version.
53 :returns: Return kernel version as a string
55 return platform.release()
58 """Get CPU information.
60 :returns: Return CPU information as a string
62 cpu = match_line('/proc/cpuinfo', 'model name')
63 return cpu.split(':')[1] if cpu else cpu
66 """Get NIC(s) information.
68 :returns: Return NIC(s) information as a list
71 output = subprocess.check_output('lspci', shell=True)
72 output = output.decode(locale.getdefaultlocale()[1])
73 for line in output.split('\n'):
74 for nic_pciid in S.getValue('WHITELIST_NICS'):
75 if line.startswith(nic_pciid):
76 nics.append(''.join(line.split(':')[2:]).strip())
80 """Get platform information.
82 Currently this is the motherboard vendor, name and socket
85 :returns: Return platform information as a string
89 with open('/sys/class/dmi/id/board_vendor', 'r') as file_:
90 output.append(file_.readline().rstrip())
92 with open('/sys/class/dmi/id/board_name', 'r') as file_:
93 output.append(file_.readline().rstrip())
95 num_nodes = len([name for name in os.listdir(
96 '/sys/devices/system/node/') if name.startswith('node')])
97 output.append(''.join(['[', str(num_nodes), ' sockets]']))
99 return ' '.join(output).strip()
102 """Get number of CPU cores.
104 :returns: Return number of CPU cores
107 with open('/proc/cpuinfo') as file_:
109 if line.rstrip('\n').startswith('processor'):
113 # this code must be executed by at leat one core...
119 """Get memory information.
121 :returns: amount of system memory as string together with unit
123 memory = match_line('/proc/meminfo', 'MemTotal')
124 return memory.split(':')[1].strip() if memory else memory
126 def get_memory_bytes():
127 """Get memory information in bytes
129 :returns: amount of system memory
131 mem_list = get_memory().split(' ')
132 mem = float(mem_list[0].strip())
133 if mem_list.__len__() > 1:
134 unit = mem_list[1].strip().lower()
146 def get_pids(proc_names_list):
147 """ Get pid(s) of process(es) with given name(s)
149 :returns: list with pid(s) of given processes or None if processes
150 with given names are not running
154 pids = subprocess.check_output(['sudo', 'LC_ALL=' + S.getValue('DEFAULT_CMD_LOCALE'), 'pidof']
156 except subprocess.CalledProcessError:
157 # such process isn't running
160 return list(map(str, map(int, pids.split())))
162 def get_pid(proc_name_str):
163 """ Get pid(s) of process with given name
165 :returns: list with pid(s) of given process or None if process
166 with given name is not running
168 return get_pids([proc_name_str])
170 # This function uses long switch per purpose, so let us suppress pylint warning too-many-branches
171 # pylint: disable=R0912
172 def get_version(app_name):
173 """ Get version of given application and its git tag
175 :returns: dictionary {'name' : app_name, 'version' : app_version, 'git_tag' : app_git_tag) in case that
176 version or git tag are not known or not applicaple, than None is returned for any unknown value
180 'ovs' : os.path.join(S.getValue('OVS_DIR'), 'include/openvswitch/version.h'),
181 'dpdk' : os.path.join(S.getValue('RTE_SDK'), 'lib/librte_eal/common/include/rte_version.h'),
182 'qemu' : os.path.join(S.getValue('QEMU_DIR'), 'VERSION'),
183 'l2fwd' : os.path.join(S.getValue('ROOT_DIR'), 'src/l2fwd/l2fwd.c'),
184 'ixnet' : os.path.join(S.getValue('TRAFFICGEN_IXNET_LIB_PATH'), 'pkgIndex.tcl')
188 def get_git_tag(path):
189 """ get tag of recent commit from repository located at 'path'
191 :returns: git tag in form of string with commit hash or None if there
192 isn't any git repository at given path
195 if os.path.isdir(path):
196 return subprocess.check_output('cd {}; git rev-parse HEAD'.format(path), shell=True,
197 stderr=subprocess.DEVNULL).decode().rstrip('\n')
198 elif os.path.isfile(path):
199 return subprocess.check_output('cd $(dirname {}); git log -1 --pretty="%H" {}'.format(path, path),
200 shell=True, stderr=subprocess.DEVNULL).decode().rstrip('\n')
203 except subprocess.CalledProcessError:
210 if app_name.lower().startswith('ovs'):
211 app_version = match_line(app_version_file['ovs'], '#define OVS_PACKAGE_VERSION')
213 app_version = app_version.split('"')[1]
214 app_git_tag = get_git_tag(S.getValue('OVS_DIR'))
215 elif app_name.lower() in ['dpdk', 'testpmd']:
216 tmp_ver = ['', '', '']
218 with open(app_version_file['dpdk']) as file_:
222 if line.startswith('#define RTE_VER_MAJOR'):
224 tmp_ver[0] = line.rstrip('\n').split(' ')[2]
225 if line.startswith('#define RTE_VER_MINOR'):
227 tmp_ver[1] = line.rstrip('\n').split(' ')[2]
228 if line.startswith('#define RTE_VER_PATCH_LEVEL'):
230 tmp_ver[2] = line.rstrip('\n').split(' ')[2]
233 app_version = '.'.join(tmp_ver)
234 app_git_tag = get_git_tag(S.getValue('RTE_SDK'))
235 elif app_name.lower().startswith('qemu'):
236 app_version = match_line(app_version_file['qemu'], '')
237 app_git_tag = get_git_tag(S.getValue('QEMU_DIR'))
238 elif app_name.lower() == 'ixnet':
239 app_version = match_line(app_version_file['ixnet'], 'package provide IxTclNetwork')
241 app_version = app_version.split(' ')[3]
242 elif app_name.lower() == 'dummy':
243 # get git tag of file with Dummy implementation
244 app_git_tag = get_git_tag(os.path.join(S.getValue('ROOT_DIR'), 'tools/pkt_gen/dummy/dummy.py'))
245 elif app_name.lower() == 'vswitchperf':
246 app_git_tag = get_git_tag(S.getValue('ROOT_DIR'))
247 elif app_name.lower() == 'l2fwd':
248 app_version = match_line(app_version_file[app_name], 'MODULE_VERSION')
250 app_version = app_version.split('"')[1]
251 app_git_tag = get_git_tag(app_version_file[app_name])
252 elif app_name.lower() in ['linux_bridge', 'buildin']:
253 # without login into running VM, it is not possible to check bridge_utils version
257 return {'name' : app_name, 'version' : app_version, 'git_tag' : app_git_tag}