Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 31 additions & 18 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@
configure_fixed_ip,
ensure_batman_mesh,
is_qemu_target,
lime_report_dir,
lime_report_filename,
resolve_target_yaml,
save_lime_report,
suppress_kernel_console,
)

Expand Down Expand Up @@ -181,20 +184,32 @@ def collect_lime_report(pytestconfig):

Runs as a session-scoped autouse fixture so it tears down BEFORE
labgrid's ``env.cleanup()`` — the SSHDriver is still active here.
Writes the output to the path in ``LIME_REPORT_OUTPUT`` if set.

Output path: ``LIME_REPORT_OUTPUT`` if set, otherwise
``lime-report.md`` inside the directory resolved by
:func:`lime_helpers.lime_report_dir` (``LIME_REPORT_DIR`` or the
``--lg-log`` directory). Every CI job passes ``--lg-log``, so physical
and QEMU runs both end with a report next to the console logs.

Resolves the labgrid target lazily via pytestconfig.stash instead of
depending on the ``target`` fixture directly, mirroring the pattern used
by ``setup_env``. This is required because multi-node mesh tests
(conftest_mesh.py) run without ``--lg-env`` and therefore labgrid never
creates an ``env``. If this fixture depended on ``target``, every mesh
session would be aborted with ``missing environment config (use --lg-env)``.
Mesh sessions collect one report per node in the ``mesh_nodes`` teardown
(conftest_mesh.py), while the VMs/DUTs are still up.
"""
yield

report_path = os.environ.get("LIME_REPORT_OUTPUT")
if not report_path:
return
explicit_output = os.environ.get("LIME_REPORT_OUTPUT", "").strip()
if explicit_output:
report_path = Path(explicit_output)
else:
report_dir = lime_report_dir(pytestconfig)
if report_dir is None:
return
report_path = report_dir / lime_report_filename()

try:
from labgrid.pytestplugin.hooks import LABGRID_ENV_KEY
Expand All @@ -204,27 +219,25 @@ def collect_lime_report(pytestconfig):
env = None

if env is None:
# No labgrid env active (typical for multi-node mesh tests): skip
# lime-report silently; mesh-specific reporting lives in conftest_mesh.
# No labgrid env active (multi-node mesh session): the per-node
# reports are written by the mesh_nodes fixture teardown.
return

try:
target = env.get_target()
if target is None:
return
ssh = target.get_driver("SSHDriver")
stdout, stderr, rc = ssh.run("lime-report", timeout=60)
output = "\n".join(stdout).strip()
if not output:
output = "_lime-report ran but produced no output._"
Path(report_path).write_text(output)
print(
f"\nlime-report collected: {len(output)} bytes → {report_path}", flush=True
)
except Exception as exc:
except Exception as exc: # noqa: BLE001 - report collection must not abort teardown
msg = f"_Could not collect lime-report: {exc}_"
print(f"\n[WARN] {msg}", file=__import__("sys").stderr, flush=True)
print(f"\n[WARN] {msg}", file=sys.stderr, flush=True)
try:
Path(report_path).write_text(msg)
except Exception:
report_path.parent.mkdir(parents=True, exist_ok=True)
report_path.write_text(msg + "\n")
except OSError:
pass
return

ok = save_lime_report(report_path, ssh.run)
status = "collected" if ok else "NOT collected (see file for reason)"
print(f"\nlime-report {status} → {report_path}", flush=True)
74 changes: 66 additions & 8 deletions tests/conftest_mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,14 @@

import pytest
from conftest_vlan import _resolve_proxy_host
from lime_helpers import REPO_ROOT, generate_mesh_ssh_ip, resolve_target_yaml
from lime_helpers import (
REPO_ROOT,
generate_mesh_ssh_ip,
lime_report_dir,
lime_report_filename,
resolve_target_yaml,
save_lime_report,
)

# Allow importing scripts from repo root
if str(REPO_ROOT) not in sys.path:
Expand Down Expand Up @@ -273,6 +280,29 @@ def run(
except subprocess.TimeoutExpired:
return [], ["SSH command timed out"], 1

def run_raw(
self, command: str, timeout: int = SSH_COMMAND_TIMEOUT
) -> tuple[list[str], list[str], int]:
"""Like :meth:`run` but keeps blank lines and does not retry.

Used for long, formatted output such as ``lime-report`` (Markdown),
where dropping empty lines breaks the layout.
"""
try:
result = subprocess.run(
self._build_ssh_cmd(command),
capture_output=True,
text=True,
timeout=timeout,
)
except subprocess.TimeoutExpired:
return [], ["SSH command timed out"], 1
return (
result.stdout.splitlines(),
result.stderr.splitlines(),
result.returncode,
)


@dataclass
class MeshNode:
Expand Down Expand Up @@ -547,7 +577,28 @@ def _configure_vwifi_node(
return rc == 0


def _mesh_nodes_virtual():
def _collect_mesh_lime_reports(config, nodes: list["MeshNode"]) -> None:
"""Write one ``lime-report-<place>.md`` per mesh node before teardown.

Destination is :func:`lime_helpers.lime_report_dir` (``LIME_REPORT_DIR``
or the ``--lg-log`` directory). Failures are logged, never raised, so a
node that died mid-session does not hide the reports of the others.
"""
report_dir = lime_report_dir(config)
if report_dir is None or not nodes:
return
for node in nodes:
path = report_dir / lime_report_filename(node.place)
ok = save_lime_report(path, node.ssh.run_raw)
logger.info(
"Node %s: lime-report %s → %s",
node.place,
"collected" if ok else "NOT collected",
path,
)


def _mesh_nodes_virtual(config=None):
"""Launch virtual mesh (QEMU + vwifi) and yield MeshNode list.

Uses LG_VIRTUAL_MESH=1, VIRTUAL_MESH_IMAGE, VIRTUAL_MESH_NODES.
Expand Down Expand Up @@ -628,10 +679,12 @@ def _mesh_nodes_virtual():
)
_wait_for_network(mesh_nodes_list, timeout=settle_timeout)

yield mesh_nodes_list

logger.info("Tearing down %d virtual mesh nodes", len(mesh_nodes_list))
cleanup()
try:
yield mesh_nodes_list
finally:
_collect_mesh_lime_reports(config, mesh_nodes_list)
logger.info("Tearing down %d virtual mesh nodes", len(mesh_nodes_list))
cleanup()


@pytest.fixture(scope="session")
Expand All @@ -650,7 +703,7 @@ def mesh_nodes(request, mesh_vlan_multi):
Virtual: LG_VIRTUAL_MESH=1, VIRTUAL_MESH_IMAGE, VIRTUAL_MESH_NODES.
"""
if os.environ.get("LG_VIRTUAL_MESH") == "1":
yield from _mesh_nodes_virtual()
yield from _mesh_nodes_virtual(request.config)
return

places_str = os.environ.get("LG_MESH_PLACES", "")
Expand Down Expand Up @@ -841,7 +894,12 @@ def mesh_nodes(request, mesh_vlan_multi):
)
_wait_for_network(nodes, timeout=settle_timeout)

yield nodes
try:
yield nodes
finally:
# DUTs are still powered and reachable here; the boot
# subprocesses below are what power them down.
_collect_mesh_lime_reports(request.config, nodes)
finally:
if procs:
logger.info("Tearing down %d mesh boot subprocesses", len(procs))
Expand Down
72 changes: 72 additions & 0 deletions tests/lime_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -858,3 +858,75 @@ def ensure_batman_mesh(target, place_name: str | None = None) -> bool:

logger.warning("Could not activate batman-adv mesh")
return False


# ---------------------------------------------------------------------------
# End-of-session lime-report
# ---------------------------------------------------------------------------

LIME_REPORT_TIMEOUT = _read_int_env("LIME_REPORT_TIMEOUT", 180)


def lime_report_dir(config=None) -> Path | None:
"""Return the directory where end-of-session lime-report files go.

Resolution order:
1. ``LIME_REPORT_DIR`` env var.
2. Parent directory of ``LIME_REPORT_OUTPUT`` (legacy single-file knob).
3. labgrid's ``--lg-log`` directory, so every CI job that already uploads
its log directory gets the report without extra configuration.

Returns ``None`` when none of them is set (local runs without logging).
"""
explicit = os.environ.get("LIME_REPORT_DIR", "").strip()
if explicit:
return Path(explicit)
output = os.environ.get("LIME_REPORT_OUTPUT", "").strip()
if output:
return Path(output).parent
option = getattr(config, "option", None)
lg_log = getattr(option, "lg_log", None)
if lg_log:
return Path(lg_log)
return None


def lime_report_filename(label: str | None = None) -> str:
"""``lime-report.md`` for single-node runs, ``lime-report-<label>.md`` per mesh node."""
if not label:
return "lime-report.md"
safe = re.sub(r"[^A-Za-z0-9._-]+", "_", label).strip("_") or "node"
return f"lime-report-{safe}.md"


def save_lime_report(path: Path, run) -> bool:
"""Run ``lime-report`` through *run* and write its output to *path*.

*run* must behave like ``SSHDriver.run``: ``run(cmd, timeout=...)``
returning ``(stdout_lines, stderr_lines, exit_code)``. Never raises: when
the DUT cannot be reached the file still gets written with the reason,
so a missing report is distinguishable from a report that was never
attempted. Returns ``True`` when real report output was captured.
"""
ok = False
try:
stdout, stderr, rc = run("lime-report", timeout=LIME_REPORT_TIMEOUT)
output = "\n".join(stdout).strip()
if output:
ok = True
else:
err = "\n".join(stderr).strip()
output = f"_lime-report produced no output (exit code {rc})._"
if err:
output += f"\n\nstderr:\n\n```\n{err}\n```"
except Exception as exc: # noqa: BLE001 - report collection must not abort teardown
output = f"_Could not collect lime-report: {exc}_"

try:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(output + "\n")
logger.info("lime-report written: %s (%d bytes)", path, len(output))
except OSError as exc:
logger.warning("Could not write lime-report to %s: %s", path, exc)
return False
return ok
Loading