Skip to content

Commit

Permalink
Move remaining functions from detect to detect_utils
Browse files Browse the repository at this point in the history
Remove test_detect
  • Loading branch information
elfosardo authored and ErwanAliasr1 committed Jul 13, 2021
1 parent 8d75297 commit 96c9863
Show file tree
Hide file tree
Showing 4 changed files with 119 additions and 150 deletions.
60 changes: 2 additions & 58 deletions hardware/detect.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
import json
import os
import pprint
from subprocess import PIPE
from subprocess import Popen
import sys

from hardware import areca
Expand All @@ -38,60 +36,6 @@
from hardware import system


AUXV_FLAGS = ["AT_HWCAP", "AT_HWCAP2", "AT_PAGESZ",
"AT_FLAGS", "AT_PLATFORM"]
# These flags may or not be present on a particular arch
AUXV_OPT_FLAGS = ["AT_BASE_PLATFORM"]


def detect_auxv(hw_lst):
new_env = os.environ.copy()
new_env["LD_SHOW_AUXV"] = "1"

cmd = Popen("/bin/true",
env=new_env,
stdout=PIPE)
stdout, err = cmd.communicate()
if err is not None:
sys.stderr.write("Info: AUXV output received\n")
return

auxv = dict()
supported_flags = AUXV_FLAGS + AUXV_OPT_FLAGS
for line in stdout.decode("utf-8").splitlines():
k, v = [i.strip() for i in line.split(":")]
if k in supported_flags:
auxv[k[3:].lower()] = v
hw_lst.append(('hw', 'auxv', k[3:].lower(), v))


def parse_ahci(hrdw, words):
if len(words) < 4:
return
if "flags" in words[2]:
flags = ""
for flag in sorted(words[3:]):
flags = "%s %s" % (flags, flag)
hrdw.append(('ahci', words[1], "flags", flags.strip()))


def parse_dmesg(hrdw):
"""Run dmesg and parse the output."""

_, output = detect_utils.cmd("dmesg")
for line in output.split('\n'):
words = line.strip().split(" ")

if words[0].startswith("[") and words[0].endswith("]"):
words = words[1:]

if not words:
continue

if "ahci" in words[0]:
parse_ahci(hrdw, words)


def parse_args(arguments):
"""Arguments parser."""

Expand Down Expand Up @@ -140,8 +84,8 @@ def main():
hrdw.extend(ipmi.get_ipmi_sdr())
hrdw.extend(rtc.detect_rtc_clock())

detect_auxv(hrdw)
parse_dmesg(hrdw)
detect_utils.detect_auxv(hrdw)
detect_utils.parse_dmesg(hrdw)
bios_hp.dump_hp_bios(hrdw)

if args.benchmark:
Expand Down
53 changes: 53 additions & 0 deletions hardware/detect_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,17 @@
import os
import re
import subprocess
from subprocess import Popen
import sys
import uuid


AUXV_FLAGS = ["AT_HWCAP", "AT_HWCAP2", "AT_PAGESZ",
"AT_FLAGS", "AT_PLATFORM"]
# These flags may or not be present on a particular arch
AUXV_OPT_FLAGS = ["AT_BASE_PLATFORM"]


def cmd(cmdline):
"""Equivalent of commands.getstatusoutput"""
try:
Expand Down Expand Up @@ -413,3 +420,49 @@ def modprobe(module):
status, _ = cmd('modprobe %s' % module)
if status == 0:
sys.stderr.write('Info: Probing %s failed\n' % module)


def detect_auxv(hw_lst):
new_env = os.environ.copy()
new_env["LD_SHOW_AUXV"] = "1"

auxv_cmd = Popen("/bin/true", env=new_env, stdout=subprocess.PIPE)
stdout, err = auxv_cmd.communicate()
if err is not None:
sys.stderr.write("Info: AUXV output received\n")
return

auxv = dict()
supported_flags = AUXV_FLAGS + AUXV_OPT_FLAGS
for line in stdout.decode("utf-8").splitlines():
k, v = [i.strip() for i in line.split(":")]
if k in supported_flags:
auxv[k[3:].lower()] = v
hw_lst.append(('hw', 'auxv', k[3:].lower(), v))


def parse_ahci(hrdw, words):
if len(words) < 4:
return
if "flags" in words[2]:
flags = ""
for flag in sorted(words[3:]):
flags = "%s %s" % (flags, flag)
hrdw.append(('ahci', words[1], "flags", flags.strip()))


def parse_dmesg(hrdw):
"""Run dmesg and parse the output."""

_, output = cmd("dmesg")
for line in output.split('\n'):
words = line.strip().split(" ")

if words[0].startswith("[") and words[0].endswith("]"):
words = words[1:]

if not words:
continue

if "ahci" in words[0]:
parse_ahci(hrdw, words)
92 changes: 0 additions & 92 deletions hardware/tests/test_detect.py

This file was deleted.

64 changes: 64 additions & 0 deletions hardware/tests/test_detect_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,3 +220,67 @@ def test_get_cpus_ppc64le(self, mock_output_lines, mock_throws_ioerror):
# NOTE(tonyb): We can't use assert_has_calls() because it's too
# permissive. We want an exact match
self.assertEqual(calls, mock_throws_ioerror.mock_calls)

@mock.patch('hardware.detect_utils.cmd',
return_value=(0, sample('dmesg')),
autospec=True)
def test_parse_dmesg(self, mock_cmd):
hw = []
detect_utils.parse_dmesg(hw)
self.assertEqual(hw, [('ahci', '0000:00:1f.2:', 'flags',
'64bit apst clo ems led '
'ncq part pio slum sntf')])

@mock.patch.object(detect_utils, 'Popen')
@mock.patch('os.environ.copy')
def test_detect_auxv_x86_succeed(self, mock_environ_copy, mock_popen):
test_data = {
'AT_HWCAP': ('hwcap', 'bfebfbff'),
'AT_HWCAP2': ('hwcap2', '0x0'),
'AT_PAGESZ': ('pagesz', '4096'),
'AT_FLAGS': ('flags', '0x0'),
'AT_PLATFORM': ('platform', 'x86_64'),
}

process_mock = mock.Mock()
attrs = {'communicate.return_value': (
sample('auxv_x86').encode('utf-8'), None)}
process_mock.configure_mock(**attrs)
mock_popen.return_value = process_mock

hw = []
detect_utils.detect_auxv(hw)

# NOTE(mrda): x86 doesn't have AUXV_OPT_FLAGS
for k in detect_utils.AUXV_FLAGS:
t = ('hw', 'auxv', test_data[k][0], test_data[k][1])
self.assertTrue(t in hw)

@mock.patch.object(detect_utils, 'Popen')
@mock.patch('os.environ.copy')
def test_detect_auxv_ppc8_succeed(self, mock_environ_copy, mock_popen):
test_data = {
'AT_HWCAP': ('hwcap',
'true_le archpmu vsx arch_2_06 dfp ic_snoop smt '
'mmu fpu altivec ppc64 ppc32'),
'AT_HWCAP2': ('hwcap2', 'htm-nosc vcrypto tar isel ebb dscr '
'htm arch_2_07'),
'AT_PAGESZ': ('pagesz', '65536'),
'AT_FLAGS': ('flags', '0x0'),
'AT_PLATFORM': ('platform', 'power8'),
'AT_BASE_PLATFORM': ('base_platform', 'power8'),
}

process_mock = mock.Mock()
attrs = {'communicate.return_value': (
sample('auxv_ppc8').encode('utf-8'), None)}
process_mock.configure_mock(**attrs)
mock_popen.return_value = process_mock

hw = []
detect_utils.detect_auxv(hw)

ppc_flags = detect_utils.AUXV_FLAGS + detect_utils.AUXV_OPT_FLAGS
for k in ppc_flags:
t = ('hw', 'auxv', test_data[k][0], test_data[k][1])
self.assertTrue(t in hw)

0 comments on commit 96c9863

Please sign in to comment.