arm/fvp: Join cli arguments in verbose logging
PATCH 1/5 arm/fvp: Join cli arguments in verbose logging
From: Peter Hoyes <[email protected]>
It is sometimes helpful to copy and paste the cli arguments from the verbose runfvp output (e.g. to test with a development FVP build), but currently the arguments are printed as a Python list. Use shlex.join(cli) to safely join the arguments together in form that can be reused directly in a shell.
Issue-Id: SCM-5314
--- meta-arm/lib/fvp/runner.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
meta-arm/lib/fvp/runner.py +2 -1
@@ -2,6 +2,7 @@ import asyncio import re import subprocess import os +import shlex import shutil import sys
@@ -67,7 +68,7 @@ class FVPRunner: if name in os.environ: env[name] = os.environ[name] - self._logger.debug(f"Constructed FVP call: {cli}") + self._logger.debug(f"Constructed FVP call: {shlex.join(cli)}") self._fvp_process = await asyncio.create_subprocess_exec( *cli, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
Signature · 1 line
2.25.1
PATCH 2/5 arm/lib: Factor out asyncio in FVPRunner
From: Peter Hoyes <[email protected]>
FVPRunner relies heavily on asyncio, despite there being very little concurrent work happening. Additionally, while the runfvp entry point starts an asyncio runner, it is not practical to have a single asyncio runtime during testimage, which is fully synchronous.
Refactor to use subprocess.Popen and related functionality. The process object has a similar interface to its async equivalent.
Cascade the API changes to runfvp and the test target classes.
Issue-Id: SCM-5314
--- meta-arm/lib/fvp/runner.py | 35 +++++++++--------- meta-arm/lib/oeqa/controllers/fvp.py | 41 +++++++--------------- meta-arm/lib/oeqa/selftest/cases/runfvp.py | 16 ++++----- scripts/runfvp | 23 +++++------- 4 files changed, 46 insertions(+), 69 deletions(-)
meta-arm/lib/fvp/runner.py +17 -18
@@ -1,4 +1,3 @@ -import asyncio import re import subprocess import os
@@ -57,7 +56,7 @@ class FVPRunner: def add_line_callback(self, callback): self._line_callbacks.append(callback) - async def start(self, config, extra_args=[], terminal_choice="none"): + def start(self, config, extra_args=[], terminal_choice="none"): cli = cli_from_config(config, terminal_choice) cli += extra_args
@@ -69,8 +68,8 @@ class FVPRunner: env[name] = os.environ[name] self._logger.debug(f"Constructed FVP call: {shlex.join(cli)}") - self._fvp_process = await asyncio.create_subprocess_exec( - *cli, + self._fvp_process = subprocess.Popen( + cli, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env)
@@ -82,13 +81,13 @@ class FVPRunner: self._terminal_ports[terminal] = port self.add_line_callback(detect_terminals) - async def stop(self): + def stop(self): if self._fvp_process: self._logger.debug(f"Terminating FVP PID {self._fvp_process.pid}") try: self._fvp_process.terminate() - await asyncio.wait_for(self._fvp_process.wait(), 10.0) - except asyncio.TimeoutError: + self._fvp_process.wait(10.0) + except subprocess.TimeoutExpired: self._logger.debug(f"Killing FVP PID {self._fvp_process.pid}") self._fvp_process.kill() except ProcessLookupError:
@@ -97,8 +96,8 @@ class FVPRunner: for telnet in self._telnets: try: telnet.terminate() - await asyncio.wait_for(telnet.wait(), 10.0) - except asyncio.TimeoutError: + telnet.wait(10.0) + except subprocess.TimeoutExpired: telnet.kill() except ProcessLookupError: pass
@@ -118,34 +117,34 @@ class FVPRunner: else: return 0 - async def run(self, until=None): + def run(self, until=None): if until and until(): return - async for line in self._fvp_process.stdout: + for line in self._fvp_process.stdout: line = line.strip().decode("utf-8", errors="replace") for callback in self._line_callbacks: callback(line) if until and until(): return - async def _get_terminal_port(self, terminal, timeout): + def _get_terminal_port(self, terminal): def terminal_exists(): return terminal in self._terminal_ports - await asyncio.wait_for(self.run(terminal_exists), timeout) + self.run(terminal_exists) return self._terminal_ports[terminal] - async def create_telnet(self, terminal, timeout=15.0): + def create_telnet(self, terminal): check_telnet() - port = await self._get_terminal_port(terminal, timeout) - telnet = await asyncio.create_subprocess_exec("telnet", "localhost", str(port), stdin=sys.stdin, stdout=sys.stdout) + port = self._get_terminal_port(terminal) + telnet = subprocess.Popen(["telnet", "localhost", str(port)], stdin=sys.stdin, stdout=sys.stdout) self._telnets.append(telnet) return telnet - async def create_pexpect(self, terminal, timeout=15.0, **kwargs): + def create_pexpect(self, terminal, **kwargs): check_telnet() import pexpect - port = await self._get_terminal_port(terminal, timeout) + port = self._get_terminal_port(terminal) instance = pexpect.spawn(f"telnet localhost {port}", **kwargs) self._pexpects.append(instance) return instance
meta-arm/lib/oeqa/controllers/fvp.py +13 -28
78 lines not on this page · raw message
meta-arm/lib/oeqa/selftest/cases/runfvp.py +8 -8
@@ -81,13 +81,13 @@ class ConfFileTests(OESelftestTestCase): class RunnerTests(OESelftestTestCase): def create_mock(self): - return unittest.mock.patch("asyncio.create_subprocess_exec") + return unittest.mock.patch("subprocess.Popen") def test_start(self): from fvp import runner with self.create_mock() as m: fvp = runner.FVPRunner(self.logger) - asyncio.run(fvp.start({ + fvp.start({ "fvp-bindir": "/usr/bin", "exe": "FVP_Binary", "parameters": {'foo': 'bar'},
@@ -96,13 +96,13 @@ class RunnerTests(OESelftestTestCase): "terminals": {}, "args": ['--extra-arg'], "env": {"FOO": "BAR"} - })) + }) - m.assert_called_once_with('/usr/bin/FVP_Binary', + m.assert_called_once_with(['/usr/bin/FVP_Binary', '--parameter', 'foo=bar', '--data', 'data1', '--application', 'a1=file', - '--extra-arg', + '--extra-arg'], stdin=unittest.mock.ANY, stdout=unittest.mock.ANY, stderr=unittest.mock.ANY,
@@ -113,7 +113,7 @@ class RunnerTests(OESelftestTestCase): from fvp import runner with self.create_mock() as m: fvp = runner.FVPRunner(self.logger) - asyncio.run(fvp.start({ + fvp.start({ "fvp-bindir": "/usr/bin", "exe": "FVP_Binary", "parameters": {},
@@ -122,9 +122,9 @@ class RunnerTests(OESelftestTestCase): "terminals": {}, "args": [], "env": {"FOO": "BAR"} - })) + }) - m.assert_called_once_with('/usr/bin/FVP_Binary', + m.assert_called_once_with(['/usr/bin/FVP_Binary'], stdin=unittest.mock.ANY, stdout=unittest.mock.ANY, stderr=unittest.mock.ANY,
scripts/runfvp +8 -15
@@ -1,6 +1,5 @@ #! /usr/bin/env python3 -import asyncio import os import pathlib import signal
@@ -47,11 +46,10 @@ def parse_args(arguments): logger.debug(f"FVP arguments: {fvp_args}") return args, fvp_args - -async def start_fvp(args, config, extra_args): +def start_fvp(args, config, extra_args): fvp = runner.FVPRunner(logger) try: - await fvp.start(config, extra_args, args.terminals) + fvp.start(config, extra_args, args.terminals) if args.console: fvp.add_line_callback(lambda line: logger.debug(f"FVP output: {line}"))
@@ -59,15 +57,16 @@ async def start_fvp(args, config, extra_args): if not expected_terminal: logger.error("--console used but FVP_CONSOLE not set in machine configuration") return 1 - telnet = await fvp.create_telnet(expected_terminal) - await telnet.wait() + telnet = fvp.create_telnet(expected_terminal) + telnet.wait() logger.debug(f"Telnet quit, cancelling tasks") else: fvp.add_line_callback(lambda line: print(line)) - await fvp.run() + fvp.run() finally: - await fvp.stop() + fvp.stop() + def runfvp(cli_args): args, extra_args = parse_args(cli_args)
@@ -77,14 +76,8 @@ def runfvp(cli_args): config_file = conffile.find(args.config) logger.debug(f"Loading {config_file}") config = conffile.load(config_file) + start_fvp(args, config, extra_args) - try: - # When we can assume Py3.7+, this can simply be asyncio.run() - loop = asyncio.get_event_loop() - return loop.run_until_complete(start_fvp(args, config, extra_args)) - except asyncio.CancelledError: - # This means telnet exited, which isn't an error - return 0 if __name__ == "__main__": try:
Signature · 1 line
2.25.1
PATCH 3/5 arm/lib: Decouple console parsing from the FVPRunner
In reply to Peter HoyesFrom: Peter Hoyes <[email protected]>
To simplify the FVPRunner class, create a separate ConsolePortParser class to handle reading an iterator of lines and parsing port numbers for FVP consoles. Use this in runfvp and the test targets.
This refactor also allows the stream being monitored to be changed more easily, e.g. to a log file.
Issue-Id: SCM-5314
--- meta-arm/lib/fvp/runner.py | 66 ++++++++++++++-------------- meta-arm/lib/oeqa/controllers/fvp.py | 17 +++---- scripts/runfvp | 9 ++-- 3 files changed, 47 insertions(+), 45 deletions(-)
meta-arm/lib/fvp/runner.py +33 -33
@@ -44,18 +44,39 @@ def check_telnet(): if not bool(shutil.which("telnet")): raise RuntimeError("Cannot find telnet, this is needed to connect to the FVP.") + +class ConsolePortParser: + def __init__(self, lines): + self._lines = lines + self._console_ports = {} + + def parse_port(self, console): + if console in self._console_ports: + return self._console_ports[console] + + while True: + try: + line = next(self._lines).strip().decode(errors='ignore') + m = re.match(r"^(\S+): Listening for serial connection on port (\d+)$", line) + if m: + matched_console = m.group(1) + matched_port = int(m.group(2)) + if matched_console == console: + return matched_port + else: + self._console_ports[matched_console] = matched_port + except StopIteration: + # self._lines might be a growing log file + pass + + class FVPRunner: def __init__(self, logger): - self._terminal_ports = {} - self._line_callbacks = [] self._logger = logger self._fvp_process = None self._telnets = [] self._pexpects = [] - def add_line_callback(self, callback): - self._line_callbacks.append(callback) - def start(self, config, extra_args=[], terminal_choice="none"): cli = cli_from_config(config, terminal_choice) cli += extra_args
@@ -73,14 +94,6 @@ class FVPRunner: stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env) - def detect_terminals(line): - m = re.match(r"^(\S+): Listening for serial connection on port (\d+)$", line) - if m: - terminal = m.group(1) - port = int(m.group(2)) - self._terminal_ports[terminal] = port - self.add_line_callback(detect_terminals) - def stop(self): if self._fvp_process: self._logger.debug(f"Terminating FVP PID {self._fvp_process.pid}")
@@ -117,34 +130,21 @@ class FVPRunner: else: return 0 - def run(self, until=None): - if until and until(): - return + def wait(self, timeout): + self._fvp_process.wait(timeout) - for line in self._fvp_process.stdout: - line = line.strip().decode("utf-8", errors="replace") - for callback in self._line_callbacks: - callback(line) - if until and until(): - return + @property + def stdout(self): + return self._fvp_process.stdout - def _get_terminal_port(self, terminal): - def terminal_exists(): - return terminal in self._terminal_ports - self.run(terminal_exists) - return self._terminal_ports[terminal] - - def create_telnet(self, terminal): + def create_telnet(self, port): check_telnet() - port = self._get_terminal_port(terminal) telnet = subprocess.Popen(["telnet", "localhost", str(port)], stdin=sys.stdin, stdout=sys.stdout) self._telnets.append(telnet) return telnet - def create_pexpect(self, terminal, **kwargs): - check_telnet() + def create_pexpect(self, port, **kwargs): import pexpect - port = self._get_terminal_port(terminal) instance = pexpect.spawn(f"telnet localhost {port}", **kwargs) self._pexpects.append(instance) return instance
meta-arm/lib/oeqa/controllers/fvp.py +9 -8
@@ -52,8 +52,10 @@ class OEFVPTarget(OEFVPSSHTarget): self.boot_timeout = 10 * 60 def _after_start(self): + parser = runner.ConsolePortParser(self.fvp.stdout) self.logger.debug(f"Awaiting console on terminal {self.config['consoles']['default']}") - console = self.fvp.create_pexpect(self.config['consoles']['default']) + port = parser.parse_port(self.config['consoles']['default']) + console = self.fvp.create_pexpect(port) try: console.expect("login\\:", timeout=self.boot_timeout) self.logger.debug("Found login prompt")
@@ -85,12 +87,6 @@ class OEFVPSerialTarget(OEFVPSSHTarget): self.test_log_suffix = pathlib.Path(bootlog).suffix self.bootlog = bootlog - def _add_terminal(self, name, fvp_name): - logfile = self._create_logfile(name) - self.logger.info(f'Creating terminal {name} on {fvp_name}') - self.terminals[name] = \ - self.fvp.create_pexpect(fvp_name, logfile=logfile) - def _create_logfile(self, name): fvp_log_file = f"{name}_log{self.test_log_suffix}" fvp_log_path = pathlib.Path(self.test_log_path, fvp_log_file)
@@ -103,8 +99,13 @@ class OEFVPSerialTarget(OEFVPSSHTarget): return open(fvp_log_path, 'wb') def _after_start(self): + parser = runner.ConsolePortParser(self.fvp.stdout) for name, console in self.config["consoles"].items(): - self._add_terminal(name, console) + logfile = self._create_logfile(name) + self.logger.info(f'Creating terminal {name} on {console}') + port = parser.parse_port(console) + self.terminals[name] = \ + self.fvp.create_pexpect(port, logfile=logfile) # testimage.bbclass expects to see a log file at `bootlog`, # so make a symlink to the 'default' log file
scripts/runfvp +5 -4
@@ -52,17 +52,18 @@ def start_fvp(args, config, extra_args): fvp.start(config, extra_args, args.terminals) if args.console: - fvp.add_line_callback(lambda line: logger.debug(f"FVP output: {line}")) expected_terminal = config["consoles"]["default"] if not expected_terminal: logger.error("--console used but FVP_CONSOLE not set in machine configuration") return 1 - telnet = fvp.create_telnet(expected_terminal) + parser = runner.ConsolePortParser(fvp.stdout) + port = parser.parse_port(expected_terminal) + telnet = fvp.create_telnet(port) telnet.wait() logger.debug(f"Telnet quit, cancelling tasks") else: - fvp.add_line_callback(lambda line: print(line)) - fvp.run() + for line in fvp.stdout: + print(line.strip().decode(errors='ignore')) finally: fvp.stop()
Signature · 1 line
2.25.1
PATCH 4/5 arm/oeqa: Log the FVP output in OEFVPSSHTarget
In reply to Peter HoyesFrom: Peter Hoyes <[email protected]>
It is often useful to inspect the FVP output after running the tests.
Refactor OEFVPSerialTarget._create_logfile into OEFVPSSHTarget._create_log_filename, so that all FVP test controllers are able to create secondary log files.
Pass a filehandle to the stdout argument of run_fvp so that the FVP output is asynchronously logged to a file. Change the port parsing logic to read back from the same log file instead of reading the stdout directly.
Issue-Id: SCM-5314
--- documentation/oeqa-fvp.md | 2 +- meta-arm/lib/fvp/runner.py | 4 +- meta-arm/lib/oeqa/controllers/fvp.py | 97 +++++++++++++++------------- 3 files changed, 54 insertions(+), 49 deletions(-)
documentation/oeqa-fvp.md +1 -1
@@ -4,7 +4,7 @@ OE-Core's [oeqa][OEQA] framework provides a method of performing runtime tests o Tests can be configured to run automatically post-build by setting the variable `TESTIMAGE_AUTO="1"`, e.g. in your Kas file or local.conf. -There are two main methods of testing, using different test "targets". +There are two main methods of testing, using different test "targets". Both test targets generate an additional log file with the prefix 'fvp_log' in the image recipe's `${WORKDIR}/testimage` containing the FVP's stdout. ## OEFVPTarget
meta-arm/lib/fvp/runner.py +2 -2
@@ -77,7 +77,7 @@ class FVPRunner: self._telnets = [] self._pexpects = [] - def start(self, config, extra_args=[], terminal_choice="none"): + def start(self, config, extra_args=[], terminal_choice="none", stdout=subprocess.PIPE): cli = cli_from_config(config, terminal_choice) cli += extra_args
@@ -91,7 +91,7 @@ class FVPRunner: self._logger.debug(f"Constructed FVP call: {shlex.join(cli)}") self._fvp_process = subprocess.Popen( cli, - stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + stdin=subprocess.DEVNULL, stdout=stdout, stderr=subprocess.STDOUT, env=env) def stop(self):
meta-arm/lib/oeqa/controllers/fvp.py +51 -46
150 lines not on this page · raw message
Signature · 1 line
2.25.1
PATCH 5/5 runfvp: Fix verbose output when using --console
In reply to Peter HoyesFrom: Peter Hoyes <[email protected]>
Start a new thread to simultaneously log the output of FVP and the telnet output if the --verbose flag is passed to runfvp. So that ConsolePortParser can read the same stream, use itertools.tee to temporarily duplicate the stream.
Use a custom log format string with an escape character to ensure that log output always starts at the beginning of a line when interleaved with console output.
Issue-Id: SCM-5314
--- scripts/runfvp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-)
scripts/runfvp +14 -2
@@ -1,9 +1,11 @@ #! /usr/bin/env python3 +import itertools import os import pathlib import signal import sys +import threading import logging logger = logging.getLogger("RunFVP")
@@ -36,7 +38,8 @@ def parse_args(arguments): fvp_args = [] args = parser.parse_args(args=arguments) - logging.basicConfig(level=args.verbose and logging.DEBUG or logging.WARNING) + logging.basicConfig(level=args.verbose and logging.DEBUG or logging.WARNING, + format='\033[G%(levelname)s: %(message)s') # If we're hooking up the console, don't start any terminals if args.console:
@@ -56,8 +59,17 @@ def start_fvp(args, config, extra_args): if not expected_terminal: logger.error("--console used but FVP_CONSOLE not set in machine configuration") return 1 - parser = runner.ConsolePortParser(fvp.stdout) + port_stdout, log_stdout = itertools.tee(fvp.stdout, 2) + parser = runner.ConsolePortParser(port_stdout) port = parser.parse_port(expected_terminal) + + def debug_log(): + for line in log_stdout: + line = line.strip().decode(errors='ignore') + logger.debug(f'FVP output: {line}') + log_thread = threading.Thread(None, debug_log) + log_thread.start() + telnet = fvp.create_telnet(port) telnet.wait() logger.debug(f"Telnet quit, cancelling tasks")
Signature · 1 line
2.25.1
Hi Jon,
There's no rush, but our team is planning a release based on langdale and it would be beneficial to have these improvements included. Let us know what you think.
Peter
Quoted 36 lines · Peter Hoyes
From: Peter Hoyes <[email protected]>
It is sometimes helpful to copy and paste the cli arguments from the verbose runfvp output (e.g. to test with a development FVP build), but currently the arguments are printed as a Python list. Use
shlex.join(cli)to safely join the arguments together in form that can be reused directly in a shell.Issue-Id: SCM-5314
Signed-off-by Peter Hoyes <[email protected]>Change-Id Ibb5c5ed45d02e241cb3858f68740fb9d4e89357a--- meta-arm/lib/fvp/runner.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)meta-arm/lib/fvp/runner.py +2
-1@@ -2,6 +2,7 @@ import asyncio import re import subprocess import os +import shlex import shutil import sys@@ -67,7 +68,7 @@ class FVPRunner: if name in os.environ: env[name] = os.environ[name] - self._logger.debug(f"Constructed FVP call: {cli}") + self._logger.debug(f"Constructed FVP call: {shlex.join(cli)}") self._fvp_process = await asyncio.create_subprocess_exec( *cli, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
Jon Mason
AppliedQuoted 5 lines · Peter Hoyes
It is sometimes helpful to copy and paste the cli arguments from the verbose runfvp output (e.g. to test with a development FVP build), but currently the arguments are printed as a Python list. Use
shlex.join(cli)to safely join the arguments together in form that can be reused directly in a shell.
Applied, thanks!
[1/5] arm/fvp: Join cli arguments in verbose logging
commit: 721bec250d5c0430591455350c02108769ba095a
[2/5] arm/lib: Factor out asyncio in FVPRunner
commit: 81e0cf090b6b98525c3caf620214f1602de20800
[3/5] arm/lib: Decouple console parsing from the FVPRunner
commit: 2265bffdc7ed80c0a1fc74180acb6d1d46b3120c
[4/5] arm/oeqa: Log the FVP output in OEFVPSSHTarget
commit: 79e78fb31d84d0e55eda47603d76d413d48544a1
[5/5] runfvp: Fix verbose output when using --console
commit: d5f132b19920870526c3b03c6a932ebb7949f8c6Best regards,
Signature · 1 line
Jon Mason <[email protected]>