diff --git a/Tools/bench_test/README.md b/Tools/bench_test/README.md new file mode 100644 index 00000000000..311c95fdeec --- /dev/null +++ b/Tools/bench_test/README.md @@ -0,0 +1,238 @@ +# PX4 bench-test suite + +PX4 v1.18 merged a large TSAN/concurrency series (PR #27606 plus follow-ups +#27809 and #27813) that reworked mavlink locking, uORB callbacks, WorkQueue +lifetime, parameters, and dataman. CI builds NuttX firmware but never boots it. +The characteristic failure mode of this class of bug on NuttX is a silent hang +(for example a mutex that was previously zero-initialized and locked from the +wrong context), not a crash. This suite makes hangs visible on real +Pixhawk-class hardware on a bench: every operation has a timeout, and a timeout +is reported as FAIL naming exactly what stalled. + +The suite never arms the vehicle. Logging is triggered with `logger on` / +`logger off`. A hang is the finding, not a nuisance: when a check times out the +tool prints which operation stalled and exits nonzero rather than blocking. + +## Requirements + +- Python 3. +- Required: `pymavlink`, `pyserial`. +- Optional: `pyulog` (better .ulg verification; magic-byte check is used as + fallback when absent). + +``` +pip3 install --user pymavlink pyserial +pip3 install --user pyulog # optional +``` + +Finding the board on macOS: + +``` +ls /dev/tty.usbmodem* +``` + +Close QGroundControl before running anything. QGC holds the serial port and the +tools will not be able to open it. + +Every script prints `[PASS]` / `[FAIL]` per check and exits nonzero on any +failure. + +## Quick start + +Full suite over a single USB link: + +``` +./run_bench_suite.py /dev/tty.usbmodem* +``` + +Full suite with a second link (telemetry radio); enables the dual-link tests: + +``` +./run_bench_suite.py /dev/tty.usbmodem* /dev/tty.usbserial-RADIO +``` + +The operator-assisted USB re-enumeration test is not part of the automated +suite. Run it manually: + +``` +./usb_replug.py /dev/tty.usbmodem* +``` + +## Risk map + +| Test | Subsystem exercised | What a failure looks like | +| --- | --- | --- | +| boot_health | WorkQueue lifetime + uORB callback rework | Task in ERROR state, a required work queue missing, or a topic not publishing | +| usb_replug | mavlink instance lifecycle across USB re-enumeration | Heartbeat does not return, mavlink instance count changes, or free RAM grows across cycles | +| dual_link_forwarding | reworked mavlink nested-send lock path (silently deadlockable on NuttX) | Silent traffic gap > 5s on either link, param download stalls, or a link is dead afterward | +| param_torture | parameter subsystem locking | A set/readback mismatch, or the param does not persist across reboot | +| mission_torture | dataman + new mission shared-state mutex | Upload/download mismatch, or an operation stalls | +| mavftp_log | logger + MAVFTP path | Log does not start/stop, download stalls, or the .ulg fails integrity check | +| reboot_loop | boot-time initialization ordering (locked zero-init mutex bugs bite at boot) | Board does not reconnect within the cycle timeout | + +`CONNECTION` is a serial device (`/dev/tty.usbmodem*`) or `udp:IP:PORT` / +`tcp:IP:PORT`. Default baud is 57600. + +## Tests + +### boot_health + +Purpose: capture a snapshot of the running system after the WorkQueue and uORB +callback rework and check it is healthy. + +``` +./boot_health.py CONNECTION [-b BAUD] [--report-dir DIR] [--require-wq LIST] +``` + +Captures `top once`, `work_queue status`, `perf`, `uorb top -1`, +`mavlink status`, `free`, and `ver all` over the MAVLink shell into a +timestamped report dir. PASS means no task is in ERROR state, the required work +queues are present (`wq:rate_ctrl`, `wq:hp_default`, `wq:lp_default`), and +topics are publishing. A FAIL names the failing check; if the shell itself +stalls, that stall is the finding. Attach the report dir when reporting. + +Baseline diff of two report dirs (uorb rates within tolerance, work queue sets +equal): + +``` +./boot_health.py --baseline OLDDIR NEWDIR [--tolerance PCT] +``` + +### usb_replug (operator-assisted) + +Purpose: exercise mavlink instance lifecycle across USB re-enumeration. + +``` +./usb_replug.py CONNECTION [-b BAUD] [--cycles M] [--heartbeat-timeout S] [--ram-tolerance BYTES] +``` + +Guides you through unplug/replug cycles (default 5). PASS means the heartbeat +returns after each replug, the mavlink instance count stays constant, and free +RAM does not grow. A FAIL names the cycle and the failing condition; a heartbeat +that never returns within `--heartbeat-timeout` is the finding. + +### dual_link_forwarding (flagship, needs 2 links) + +Purpose: exercise the reworked mavlink nested-send lock path that was silently +deadlockable on NuttX. + +``` +./dual_link_forwarding.py CONNECTION CONNECTION2 [-b BAUD] [--baudrate2 BAUD2] [--duration S] +``` + +Verifies heartbeats on both links, then runs 60s of sustained bidirectional +traffic (a silent gap > 5s on either link is FAIL), then a full param download +over the radio link WHILE a shell session runs over USB, then proves both links +are still alive afterward. PASS means every stage completed and both links +survived. A hang anywhere reports FAIL naming the stage instead of blocking. + +### param_torture + +Purpose: hammer the parameter subsystem locking. + +``` +./param_torture.py CONNECTION [-b BAUD] [--iterations N] [--param NAME] [--skip-reboot] +``` + +Full param download, then 50 set/readback iterations on `SDLOG_UTC_OFFSET` (a +harmless scratch param, restored afterward), then param save + reboot + +persistence verification. PASS means every readback matched, the value +persisted across reboot, and the original value was restored. A FAIL names the +iteration or the persistence step. Use `--skip-reboot` to avoid the reboot +stage. + +### mission_torture + +Purpose: exercise dataman and the new mission shared-state mutex. + +``` +./mission_torture.py CONNECTION [CONNECTION2] [-b BAUD] [--baudrate2 BAUD2] [--iterations N] [--items K] +``` + +220-waypoint mission upload/download/compare/clear, 10 iterations. With two +links it alternates uploads between the links. PASS means every download matched +the upload across all iterations. A FAIL names the iteration and the mismatch, +or the operation that stalled. + +### mavftp_log + +Purpose: exercise the logger and the MAVFTP path. + +``` +./mavftp_log.py CONNECTION [-b BAUD] [--log-duration S] [--outdir DIR] +``` + +Starts a short log via `logger on` / `logger off` (no arming), downloads the +newest .ulg via MAVFTP, and verifies ULog integrity (pyulog if installed, magic +bytes otherwise). PASS means the log was created, downloaded, and passed the +integrity check. A FAIL names the stage; a stalled MAVFTP transfer is the +finding. + +### reboot_loop + +Purpose: exercise boot-time initialization ordering, where locked zero-init +mutex bugs bite. + +``` +./reboot_loop.py CONNECTION [-b BAUD] [--iterations N] [--cycle-timeout S] +``` + +10 reboot/reconnect cycles via `MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN`. PASS means +the board came back within `--cycle-timeout` on every cycle. Any failure to +reconnect in time is FAIL with the elapsed time and the cycle number. + +### run_bench_suite + +Runs all non-interactive tests in sequence with a per-test watchdog. + +``` +./run_bench_suite.py CONNECTION [CONNECTION2] [-b BAUD] [--skip NAMES] [--report-dir DIR] [--per-test-timeout S] [--stop-on-fail] +``` + +Default per-test watchdog is 900s; a test that exceeds it is killed and recorded +as FAIL ` hung`. `usb_replug` is operator-assisted and must be run +manually. Dual-link tests run only when a second connection is given. + +## Baseline workflow + +Use this to compare pre-upgrade and post-upgrade firmware. Each capture +creates a timestamped directory under `--report-dir` and prints its path +(`report dir: ...`); the diff takes those printed paths, not the base +directory: + +1. On known-good firmware, capture a report: + `./boot_health.py CONNECTION` and note the printed report dir, for + example `bench_reports/20260706T164512Z_boot_health`. +2. Flash the candidate firmware. +3. Capture again: `./boot_health.py CONNECTION` and note the new report dir. +4. Diff them: + `./boot_health.py --baseline [--tolerance PCT]` + +The diff checks that uorb rates are within tolerance and the work queue sets are +equal. A missing work queue or a rate outside tolerance is FAIL. + +## Safety + +- Bench use only. Props off. +- The suite never arms the vehicle. +- `param_torture` and `reboot_loop` reboot the board multiple times. Expect the + link to drop and return. +- `param_torture` writes only to `SDLOG_UTC_OFFSET` and restores the original + value automatically. + +## Troubleshooting + +No heartbeat: + +- Wrong device. Confirm with `ls /dev/tty.usbmodem*` and pass the exact path. +- QGroundControl (or another GCS) is holding the port. Close it. +- Wrong baud on a radio link. Match the radio's configured baud with `-b` / + `--baudrate2`. + +Shell stalls: if `boot_health` or a shell-based stage hangs, that stall is the +finding, not a tooling bug. Note which command it stalled on and keep the report +dir. + +Telemetry radio bandwidth: dual-link traffic, param download, and mission +upload/download over a radio link are much slower than over USB. Allow longer +durations (`--duration`, `--per-test-timeout`) when a radio is in the path. diff --git a/Tools/bench_test/boot_health.py b/Tools/bench_test/boot_health.py new file mode 100755 index 00000000000..4705a91c7c9 --- /dev/null +++ b/Tools/bench_test/boot_health.py @@ -0,0 +1,337 @@ +#!/usr/bin/env python3 +""" +Boot-health snapshot for a PX4 board on real NuttX hardware. + +After the v1.18 concurrency and locking rework we want a fast, repeatable +way to confirm a freshly booted board is healthy: no task stuck in an ERROR +state, the expected work queues running, uORB actually publishing, and the +MAVLink instances up. This script connects over MAVLink, opens an nsh shell +over SERIAL_CONTROL, runs a fixed set of status commands, saves each raw +output for later comparison, and reports PASS/FAIL per check. + +It also has an offline baseline mode: point it at an old report dir and a new +one and it flags uORB topics whose publication rate drifted beyond a +tolerance, topics that disappeared, and work queues that went missing. That +turns "does it still boot" into "does it still boot the same way it used to". + +Every wait has a timeout. A command that never completes is reported as a FAIL +naming the command, never a hung script, because a silent hang is exactly the +failure mode we are hunting. +""" + +import argparse +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import px4bench + + +# Commands to run in capture mode: (command, per-command timeout seconds). +# Order matters: cheap/liveness checks first, heavier dumps later. +CAPTURE_COMMANDS = [ + ('top once', 15), + ('work_queue status', 10), + ('perf', 25), + ('uorb top -1', 15), + ('mavlink status', 10), + ('free', 10), + ('ver all', 10), +] + + +def sanitize_cmd(cmd): + """Turn a shell command into a safe filename stem.""" + stem = re.sub(r'[^A-Za-z0-9]+', '_', cmd).strip('_') + return stem or 'cmd' + + +def save_output(report_dir, cmd, output): + """Write a command's raw output to /.txt.""" + path = os.path.join(report_dir, sanitize_cmd(cmd) + '.txt') + try: + with open(path, 'w') as f: + f.write(output) + except OSError as e: + print('[INFO] could not save {}: {}'.format(path, e), flush=True) + return path + + +# --------------------------------------------------------------------------- +# Parsers +# --------------------------------------------------------------------------- + +def top_has_error_task(output): + """Return (has_error, list_of_offending_lines). + + The `top` STATE column is one of the tstate_name() strings; the default / + unknown state prints as ERROR (print_load.cpp:132). STATE is a + whitespace-padded token, so we match ERROR as a standalone word. We only + look at lines that start with a PID (an integer) to avoid matching the + header or any incidental use of the word. + """ + offenders = [] + for line in output.splitlines(): + fields = line.split() + if not fields: + continue + if not fields[0].isdigit(): + continue # not a task row (header, footer, blank) + if 'ERROR' in fields[1:]: + offenders.append(line.strip()) + return (len(offenders) > 0, offenders) + + +def parse_work_queues(output): + """Return the set of work-queue names present in `work_queue status` output. + + WorkQueue::print_status prints one line per queue starting with the queue + name including its prefix, e.g. `wq:rate_ctrl`, `wq:SPI1`, `wq:lp_default` + (WorkQueue.cpp:232, names in WorkQueueManager.hpp). We extract every + `wq:` token found anywhere on a line so we tolerate leading counters + or formatting. + """ + names = set() + for line in output.splitlines(): + for m in re.findall(r'wq:[A-Za-z0-9_]+', line): + names.add(m) + return names + + +def count_mavlink_instances(output): + """Count MAVLink instances from `mavlink status`. + + Each instance block begins with `instance #N:` (mavlink_main.cpp:535). + """ + return len(re.findall(r'instance\s*#\s*\d+', output)) + + +def parse_uorb_top(output): + """Parse `uorb top -1` output into {topic_key: rate}. + + Format (uORBDeviceMaster.cpp:387-396, showTop): + header: "update: 1s, topics: N, total publications: M, X.X kB/s" + columns: "TOPIC NAME INST #SUB RATE #Q SIZE" + rows: " %2i %4i %4i %2i %4i" + = name INST #SUB RATE #Q SIZE + + So a data row is: topic name (may contain no spaces; uORB topic names are + single tokens), then five integers INST, #SUB, RATE, #Q, SIZE. RATE is the + publication rate we compare across baselines. We key each entry by + "name#inst" so multi-instance topics stay distinct, and we skip any line + that does not match tolerantly (headers, escape codes, blanks). + """ + rates = {} + # a topic name token followed by exactly five integers at end of line + row_re = re.compile(r'^([A-Za-z][A-Za-z0-9_]*)\s+' + r'(-?\d+)\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)\s*$') + for raw in output.splitlines(): + # strip any leftover ANSI escape sequences (clear-line/clear-screen) + line = re.sub(r'\x1b\[[0-9;]*[A-Za-z]', '', raw).strip() + if not line: + continue + m = row_re.match(line) + if not m: + continue + name = m.group(1) + inst = int(m.group(2)) + rate = int(m.group(4)) + rates['{}#{}'.format(name, inst)] = rate + return rates + + +# --------------------------------------------------------------------------- +# Capture mode +# --------------------------------------------------------------------------- + +def run_capture(args, report): + report_dir = px4bench.make_report_dir(args.report_dir, 'boot_health') + report.info('report dir: {}'.format(report_dir)) + + require_wq = [q.strip() for q in args.require_wq.split(',') if q.strip()] + + try: + mav = px4bench.connect(args.connection, baud=args.baudrate, + timeout=args.connect_timeout) + except (TimeoutError, OSError) as e: + report.fail('connect', str(e)) + return report_dir + report.ok('connect', 'heartbeat from {}'.format(args.connection)) + + shell = px4bench.MavlinkShell(mav) + if not shell.open(timeout=5): + report.fail('shell open', 'no nsh output on SERIAL_CONTROL within 5s') + shell.close() + mav.close() + return report_dir + report.ok('shell open', 'nsh responded') + + outputs = {} + for cmd, timeout in CAPTURE_COMMANDS: + output, timed_out = shell.run(cmd, timeout=timeout) + save_output(report_dir, cmd, output) + outputs[cmd] = output + if timed_out: + report.fail('cmd ' + cmd, + 'shell command {} stalled (no completion within {}s)'.format( + cmd, timeout)) + else: + report.ok('cmd ' + cmd, '{} bytes'.format(len(output))) + + # top: no task in ERROR state + if 'top once' in outputs and outputs['top once']: + has_err, offenders = top_has_error_task(outputs['top once']) + report.check('top no ERROR task', not has_err, + 'offending rows: ' + ' | '.join(offenders) if has_err + else 'no task in ERROR state') + + # work queues: required set present + if 'work_queue status' in outputs: + present = parse_work_queues(outputs['work_queue status']) + missing = [q for q in require_wq if q not in present] + report.check('work queues present', not missing, + 'missing: {}'.format(', '.join(missing)) if missing + else 'all required present ({} queues total)'.format(len(present))) + + # uorb: parsed at least one topic + if 'uorb top -1' in outputs: + rates = parse_uorb_top(outputs['uorb top -1']) + report.check('uorb topics parsed', len(rates) > 0, + '{} topics'.format(len(rates))) + + # mavlink instances: informational count + if 'mavlink status' in outputs: + n = count_mavlink_instances(outputs['mavlink status']) + report.info('mavlink instances: {}'.format(n)) + + shell.close() + mav.close() + return report_dir + + +# --------------------------------------------------------------------------- +# Baseline mode +# --------------------------------------------------------------------------- + +def read_saved(report_dir, cmd): + """Read a previously saved command output from a report dir, or ''.""" + path = os.path.join(report_dir, sanitize_cmd(cmd) + '.txt') + try: + with open(path) as f: + return f.read() + except OSError: + return '' + + +def run_baseline(old_dir, new_dir, tolerance, report): + report.info('baseline: OLD={} NEW={} tolerance={}%'.format(old_dir, new_dir, tolerance)) + + for d in (old_dir, new_dir): + if not os.path.isdir(d): + report.fail('baseline dir', 'not a directory: {}'.format(d)) + return + + old_uorb = read_saved(old_dir, 'uorb top -1') + new_uorb = read_saved(new_dir, 'uorb top -1') + if not old_uorb: + report.fail('baseline uorb old', 'no saved uorb output in {}'.format(old_dir)) + if not new_uorb: + report.fail('baseline uorb new', 'no saved uorb output in {}'.format(new_dir)) + + if old_uorb and new_uorb: + old_rates = parse_uorb_top(old_uorb) + new_rates = parse_uorb_top(new_uorb) + report.info('uorb topics: OLD={} NEW={}'.format(len(old_rates), len(new_rates))) + + # topics present in OLD but missing in NEW -> FAIL + for topic in sorted(old_rates): + if topic not in new_rates: + report.fail('uorb missing ' + topic, + 'present in baseline, absent now (was {} Hz)'.format(old_rates[topic])) + + # rate drift beyond tolerance -> FAIL + for topic in sorted(old_rates): + if topic not in new_rates: + continue + old_r = old_rates[topic] + new_r = new_rates[topic] + if old_r == 0: + # baseline was idle; only flag if it is now clearly active + if new_r > 0: + report.info('uorb {} went {}->{} Hz (baseline idle)'.format( + topic, old_r, new_r)) + continue + drift = abs(new_r - old_r) * 100.0 / old_r + if drift > tolerance: + report.fail('uorb rate ' + topic, + '{} Hz -> {} Hz ({:.0f}% drift > {}%)'.format( + old_r, new_r, drift, tolerance)) + + # new topics -> info only + for topic in sorted(new_rates): + if topic not in old_rates: + report.info('uorb new topic {} ({} Hz)'.format(topic, new_rates[topic])) + + # work queue name sets + old_wq_raw = read_saved(old_dir, 'work_queue status') + new_wq_raw = read_saved(new_dir, 'work_queue status') + if not old_wq_raw or not new_wq_raw: + report.info('work_queue status missing from one dir, skipping queue diff') + else: + old_wq = parse_work_queues(old_wq_raw) + new_wq = parse_work_queues(new_wq_raw) + missing = sorted(old_wq - new_wq) + report.check('work queues retained', not missing, + 'missing now: {}'.format(', '.join(missing)) if missing + else '{} queues, none lost'.format(len(old_wq))) + added = sorted(new_wq - old_wq) + if added: + report.info('new work queues: {}'.format(', '.join(added))) + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description='PX4 boot-health snapshot and offline baseline diff.') + # connection is optional so --baseline can run without hardware + parser.add_argument('connection', nargs='?', + help='MAVLink connection: serial device (/dev/tty.usbmodem01), ' + 'udp:IP:PORT, or tcp:IP:PORT') + parser.add_argument('--baudrate', '-b', type=int, default=px4bench.DEFAULT_BAUD, + help='serial baud rate (default: %(default)s)') + parser.add_argument('--connect-timeout', type=float, default=20, + help='seconds to wait for the first heartbeat (default: %(default)s)') + parser.add_argument('--report-dir', default='bench_reports', + help='base directory for report output (default: %(default)s)') + parser.add_argument('--require-wq', default='wq:rate_ctrl,wq:hp_default,wq:lp_default', + help='comma-separated work queues that must be present ' + '(default: %(default)s)') + parser.add_argument('--baseline', nargs=2, metavar=('OLDDIR', 'NEWDIR'), + help='offline mode: diff two existing report dirs, no board needed') + parser.add_argument('--tolerance', type=float, default=30, + help='baseline: max %% uORB rate drift before FAIL (default: %(default)s)') + args = parser.parse_args() + + if args.baseline: + report = px4bench.Reporter('boot_health_baseline') + run_baseline(args.baseline[0], args.baseline[1], args.tolerance, report) + sys.exit(report.finish()) + + if not args.connection: + parser.error('a CONNECTION is required unless --baseline OLDDIR NEWDIR is given') + + report = px4bench.Reporter('boot_health') + report_dir = run_capture(args, report) + code = report.finish() + print('report dir: {}'.format(report_dir)) + print('baseline later with: {} --baseline {} '.format( + os.path.basename(sys.argv[0]), report_dir)) + sys.exit(code) + + +if __name__ == '__main__': + main() diff --git a/Tools/bench_test/dual_link_forwarding.py b/Tools/bench_test/dual_link_forwarding.py new file mode 100755 index 00000000000..de19eb195fa --- /dev/null +++ b/Tools/bench_test/dual_link_forwarding.py @@ -0,0 +1,388 @@ +#!/usr/bin/env python3 +""" +Dual-link forwarding stress test for the mavlink nested-send lock path. + +This is the flagship bench test for qualifying PX4 v1.18 on real NuttX +hardware after the mavlink locking rework. The rework changed how the +mavlink module takes its send lock, and nested-send paths (a send issued +from within a handler that already holds the lock) were silently +deadlockable on NuttX. A deadlock there does not crash: it hangs. Every +byte over both links just stops. + +This test drives two links simultaneously (a USB/telemetry pair) and +hammers the nested-send path hardest in phase 3, where a full parameter +download runs over link2 while an nsh shell session and message pump run +over link1 at the same time. If the send lock can deadlock under nested +use, one of the phases will stop producing traffic and the corresponding +wait will time out. A timeout is a FAIL that names exactly what stalled. + +Nothing here arms the vehicle. A hung phase must never hang the script: +every wait is bounded and there is a global wall-clock deadline. +""" + +import argparse +import os +import sys +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from px4bench import Reporter, MavlinkShell, add_connection_args, connect + +from pymavlink import mavutil + + +HEARTBEAT_INTERVAL = 1.0 # GCS -> autopilot heartbeat cadence, seconds +MAX_SILENT_GAP = 5.0 # a gap larger than this on either link is a FAIL +SHELL_STATUS_INTERVAL = 5.0 # run `mavlink status` over link1 this often in phase 3 +SHELL_RUN_TIMEOUT = 10.0 # per shell command timeout in phase 3 +PARAM_STALL_TIMEOUT = 10.0 # no new params for this long during download -> stalled +PARAM_HARD_CAP = 120.0 # absolute cap on the param download, seconds +GLOBAL_BUDGET_EXTRA = 300.0 # wall-clock budget = duration + this + + +def send_heartbeat(mav): + mav.mav.heartbeat_send(mavutil.mavlink.MAV_TYPE_GCS, + mavutil.mavlink.MAV_AUTOPILOT_INVALID, 0, 0, 0) + + +class ParamDownloader(threading.Thread): + """Full parameter download over one link, run in a daemon worker thread. + + Exposes progress (received / expected) so a stalled download can be + reported by index. The thread stops itself if no new parameter arrives + within PARAM_STALL_TIMEOUT or the hard cap is hit. + """ + + def __init__(self, mav): + super().__init__(daemon=True) + self.mav = mav + self.received = 0 + self.expected = 0 # param_count reported by the autopilot, 0 until known + self.complete = False + self.error = None + self._seen = set() + self._last_progress = time.monotonic() + + def run(self): + try: + self._download() + except Exception as e: # noqa: BLE001 - a worker crash must be reported, not lost + self.error = repr(e) + + def _download(self): + self.mav.mav.param_request_list_send(self.mav.target_system, + self.mav.target_component) + start = time.monotonic() + self._last_progress = start + next_hb = 0.0 + while True: + now = time.monotonic() + if now > next_hb: + send_heartbeat(self.mav) + next_hb = now + HEARTBEAT_INTERVAL + if now - start > PARAM_HARD_CAP: + self.error = 'hard cap {:.0f}s hit'.format(PARAM_HARD_CAP) + return + if now - self._last_progress > PARAM_STALL_TIMEOUT: + self.error = 'no new param for {:.0f}s'.format(PARAM_STALL_TIMEOUT) + return + m = self.mav.recv_match(type='PARAM_VALUE', blocking=True, timeout=0.2) + if m is None: + continue + if self.expected == 0 and m.param_count > 0: + self.expected = m.param_count + if m.param_index not in self._seen: + self._seen.add(m.param_index) + self.received = len(self._seen) + self._last_progress = now + if self.expected > 0 and self.received >= self.expected: + self.complete = True + return + + +class LinkPump(threading.Thread): + """Pump one link in a daemon thread: read everything, track gaps and rate, + send a heartbeat every HEARTBEAT_INTERVAL. Used for phase 2 where both + links must stay live at once. + """ + + def __init__(self, mav, name, deadline): + super().__init__(daemon=True) + self.mav = mav + self.name = name + self.deadline = deadline # monotonic time to stop at + self.msgs = 0 + self.bytes = 0 + self.max_gap = 0.0 + self._stop = threading.Event() + + def stop(self): + self._stop.set() + + def run(self): + last_msg = time.monotonic() + next_hb = 0.0 + while not self._stop.is_set() and time.monotonic() < self.deadline: + now = time.monotonic() + if now > next_hb: + send_heartbeat(self.mav) + next_hb = now + HEARTBEAT_INTERVAL + m = self.mav.recv_match(blocking=True, timeout=0.1) + now = time.monotonic() + if m is None: + gap = now - last_msg + if gap > self.max_gap: + self.max_gap = gap + continue + gap = now - last_msg + if gap > self.max_gap: + self.max_gap = gap + last_msg = now + self.msgs += 1 + try: + self.bytes += len(m.get_msgbuf()) + except Exception: # noqa: BLE001 - length is best-effort accounting only + pass + + +def parse_status_instances(text): + """Parse `mavlink status` output into a list of per-instance dicts with + tx/rx B/s. Blocks start with a line containing 'instance #'. + """ + instances = [] + cur = None + for line in text.splitlines(): + stripped = line.strip() + if 'instance #' in stripped: + if cur is not None: + instances.append(cur) + cur = {'header': stripped, 'tx': None, 'rx': None} + continue + if cur is None: + continue + if stripped.startswith('tx:') and cur['tx'] is None: + cur['tx'] = stripped + elif stripped.startswith('rx:') and cur['rx'] is None: + cur['rx'] = stripped + if cur is not None: + instances.append(cur) + return instances + + +def phase1_liveness(report, mav1, mav2, global_deadline): + """Independent heartbeat check on each link. FAIL names the dead link.""" + report.info('Phase 1: liveness on both links') + for label, mav in (('link1', mav1), ('link2', mav2)): + if time.monotonic() > global_deadline: + report.fail('phase1_budget', 'global deadline hit before checking {}'.format(label)) + return False + send_heartbeat(mav) + hb = mav.wait_heartbeat(timeout=5) + if hb is None: + report.fail('phase1_heartbeat_{}'.format(label), + 'no heartbeat on {} within 5s (link dead)'.format(label)) + return False + report.ok('phase1_heartbeat_{}'.format(label), 'heartbeat received') + return True + + +def phase2_sustained(report, mav1, mav2, duration, global_deadline): + """Sustained bidirectional traffic on both links for `duration` seconds.""" + report.info('Phase 2: sustained bidirectional traffic for {}s'.format(duration)) + deadline = min(time.monotonic() + duration, global_deadline) + pump1 = LinkPump(mav1, 'link1', deadline) + pump2 = LinkPump(mav2, 'link2', deadline) + pump1.start() + pump2.start() + # Wait for the pumps to finish their window, with a hard join deadline so a + # wedged pump thread cannot hang the script. + join_deadline = deadline + 10.0 + for pump in (pump1, pump2): + remaining = max(0.1, join_deadline - time.monotonic()) + pump.join(timeout=remaining) + for pump in (pump1, pump2): + if pump.is_alive(): + pump.stop() + report.fail('phase2_pump_{}'.format(pump.name), + 'pump thread on {} did not stop (stalled)'.format(pump.name)) + return False + + elapsed = duration + for pump in (pump1, pump2): + rate_msgs = pump.msgs / elapsed if elapsed > 0 else 0.0 + rate_bytes = pump.bytes / elapsed if elapsed > 0 else 0.0 + detail = '{} msgs ({:.1f} msg/s), {} B ({:.1f} B/s), max gap {:.2f}s'.format( + pump.msgs, rate_msgs, pump.bytes, rate_bytes, pump.max_gap) + if pump.msgs == 0: + report.fail('phase2_traffic_{}'.format(pump.name), + '{}: zero messages received'.format(pump.name)) + return False + if pump.max_gap > MAX_SILENT_GAP: + report.fail('phase2_gap_{}'.format(pump.name), + '{}: silent gap {:.2f}s exceeds {:.0f}s: {}'.format( + pump.name, pump.max_gap, MAX_SILENT_GAP, detail)) + return False + report.ok('phase2_traffic_{}'.format(pump.name), detail) + return True + + +def phase3_nested_hammer(report, mav1, mav2, global_deadline): + """Param download over link2 in a worker thread WHILE link1 runs an nsh + shell (`mavlink status` every 5s) and keeps pumping. This is the nested + send lock stress: heavy simultaneous use of both links. + """ + report.info('Phase 3: nested-send hammer (param download on link2, shell on link1)') + shell = MavlinkShell(mav1) + if not shell.open(timeout=5): + report.fail('phase3_shell_open', 'nsh shell over link1 did not respond within 5s') + return False + + downloader = ParamDownloader(mav2) + downloader.start() + + hard_deadline = min(time.monotonic() + PARAM_HARD_CAP + 15.0, global_deadline) + next_status = 0.0 + shell_runs = 0 + while downloader.is_alive(): + now = time.monotonic() + if now > hard_deadline: + break + # keep link1 pumping so the autopilot keeps streaming to us + mav1.recv_match(blocking=True, timeout=0.1) + if now >= next_status: + _, timed_out = shell.run('mavlink status', timeout=SHELL_RUN_TIMEOUT) + if timed_out: + report.fail('phase3_shell_stall', + 'shell over link1 stalled during param download on link2 ' + '(param {}/{})'.format(downloader.received, downloader.expected)) + shell.close() + return False + shell_runs += 1 + next_status = now + SHELL_STATUS_INTERVAL + + # Join the worker with a hard deadline. A thread stuck past the deadline is + # itself the finding; it is a daemon so the script can still exit. + downloader.join(timeout=max(0.1, hard_deadline - time.monotonic()) + 2.0) + shell.close() + + if downloader.is_alive(): + report.fail('phase3_param_stall', + 'param download on link2 stalled at index {}/{}'.format( + downloader.received, downloader.expected)) + return False + if downloader.error is not None: + report.fail('phase3_param_download', + 'param download on link2 incomplete ({}) at {}/{}'.format( + downloader.error, downloader.received, downloader.expected)) + return False + if not downloader.complete: + report.fail('phase3_param_download', + 'param download on link2 incomplete at {}/{}'.format( + downloader.received, downloader.expected)) + return False + + report.ok('phase3_param_download', + 'downloaded {}/{} params while running {} shell status calls on link1'.format( + downloader.received, downloader.expected, shell_runs)) + report.ok('phase3_shell', '{} `mavlink status` calls completed over link1'.format(shell_runs)) + return True + + +def phase4_post_liveness(report, mav1, mav2, global_deadline): + """After the hammer, both links must still deliver a fresh heartbeat and + link1 must complete one more `mavlink status`. This proves both links + survived heavy simultaneous use. + """ + report.info('Phase 4: post-stress liveness') + for label, mav in (('link1', mav1), ('link2', mav2)): + if time.monotonic() > global_deadline: + report.fail('phase4_budget', 'global deadline hit before checking {}'.format(label)) + return False + send_heartbeat(mav) + hb = mav.wait_heartbeat(timeout=5) + if hb is None: + report.fail('phase4_heartbeat_{}'.format(label), + 'no fresh heartbeat on {} within 5s after stress'.format(label)) + return False + report.ok('phase4_heartbeat_{}'.format(label), 'link alive after stress') + + shell = MavlinkShell(mav1) + if not shell.open(timeout=5): + report.fail('phase4_shell_open', 'nsh shell over link1 did not respond after stress') + return False + out, timed_out = shell.run('mavlink status', timeout=SHELL_RUN_TIMEOUT) + shell.close() + if timed_out: + report.fail('phase4_shell_stall', '`mavlink status` over link1 stalled after stress') + return False + instances = parse_status_instances(out) + if not instances: + report.fail('phase4_status_parse', 'could not parse any instance block from mavlink status') + return False + for inst in instances: + report.info(' {} | {} | {}'.format( + inst['header'], + inst['tx'] if inst['tx'] else 'tx: ?', + inst['rx'] if inst['rx'] else 'rx: ?')) + report.ok('phase4_status', 'parsed {} mavlink instance block(s)'.format(len(instances))) + return True + + +def main(): + parser = argparse.ArgumentParser( + description='Dual-link forwarding stress of the mavlink nested-send lock path.') + add_connection_args(parser, dual_link=True) + parser.add_argument('--baudrate2', type=int, default=57600, + help='baud rate for the second connection (default: %(default)s)') + parser.add_argument('--duration', type=float, default=60, + help='sustained-traffic duration in seconds (default: %(default)s)') + args = parser.parse_args() + + if args.connection2 is None: + print('error: dual_link_forwarding requires a second connection (CONNECTION2)', + file=sys.stderr) + sys.exit(2) + + report = Reporter('dual_link_forwarding') + global_deadline = time.monotonic() + args.duration + GLOBAL_BUDGET_EXTRA + + mav1 = None + mav2 = None + try: + report.info('Connecting link1: {} @ {}'.format(args.connection, args.baudrate)) + try: + mav1 = connect(args.connection, baud=args.baudrate, timeout=args.connect_timeout) + except (TimeoutError, OSError) as e: + report.fail('connect_link1', str(e)) + sys.exit(report.finish()) + + report.info('Connecting link2: {} @ {}'.format(args.connection2, args.baudrate2)) + try: + mav2 = connect(args.connection2, baud=args.baudrate2, timeout=args.connect_timeout) + except (TimeoutError, OSError) as e: + report.fail('connect_link2', str(e)) + sys.exit(report.finish()) + + if not phase1_liveness(report, mav1, mav2, global_deadline): + sys.exit(report.finish()) + if not phase2_sustained(report, mav1, mav2, args.duration, global_deadline): + sys.exit(report.finish()) + if not phase3_nested_hammer(report, mav1, mav2, global_deadline): + sys.exit(report.finish()) + if not phase4_post_liveness(report, mav1, mav2, global_deadline): + sys.exit(report.finish()) + finally: + for mav in (mav1, mav2): + if mav is not None: + try: + mav.close() + except Exception: # noqa: BLE001 - cleanup only + pass + + sys.exit(report.finish()) + + +if __name__ == '__main__': + main() diff --git a/Tools/bench_test/mavftp_log.py b/Tools/bench_test/mavftp_log.py new file mode 100755 index 00000000000..42dc437afaf --- /dev/null +++ b/Tools/bench_test/mavftp_log.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +""" +Logger + MAVFTP download path test for PX4 v1.18 bench qualification. + +The mavlink locking rework touches every message handler that sends a +reply, which includes the FILE_TRANSFER_PROTOCOL handler that backs +MAVFTP. A burst read download is a long sequence of nested send replies, +so a deadlock in the send lock shows up here as a transfer that stops +mid-file. This test starts logging, records for a few seconds, stops and +flushes, then finds and downloads the freshest ULog over MAVFTP and +verifies it. + +No arming: `logger on` / `logger off` start and stop logging directly, +overriding arming state, as long as the logger module is running. + +Every step is bounded. A stalled transfer is a FAIL that names how many +bytes made it before the stall, not a hung script. +""" + +import argparse +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from px4bench import Reporter, MavlinkShell, add_connection_args, connect, make_report_dir + +from pymavlink import mavutil +from pymavlink import mavftp + + +LOG_ROOT = '/fs/microsd/log' +# ULog file header magic: 'U' 'L' 'o' 'g' 0x01 0x12 0x35, then a file-version +# byte. See src/modules/logger/logger.cpp:2099-2106. +ULOG_MAGIC7 = bytes([0x55, 0x4C, 0x6F, 0x67, 0x01, 0x12, 0x35]) +FTP_BUDGET = 300.0 # overall MAVFTP budget in seconds +SHELL_TIMEOUT = 10.0 +MIN_LOG_SIZE = 1024 # a real ULog is more than 1 KB + + +def send_heartbeat(mav): + mav.mav.heartbeat_send(mavutil.mavlink.MAV_TYPE_GCS, + mavutil.mavlink.MAV_AUTOPILOT_INVALID, 0, 0, 0) + + +def ftp_list(ftp, path): + """List a remote directory. cmd_list drives its own reply loop internally + and populates ftp.list_result. Returns the list of DirectoryEntry. + """ + ftp.cmd_list([path]) + return list(ftp.list_result) + + +def ftp_download(mav, ftp, remote, local, report): + """Download one remote file to a local path over MAVFTP, bounded by + FTP_BUDGET and reporting a stall by byte count. + + cmd_get only sends OpenFileRO and returns; the transfer itself is driven + by process_ftp_reply, which loops recv_match -> __mavlink_packet (burst + read handling, temp-file writes) -> __idle_task until idle or timeout. + We use a completion callback so we know the burst read finished, and we + pump process_ftp_reply in bounded slices so a stalled burst becomes a + named FAIL instead of a hang. process_ftp_reply requires its timeout to + be greater than idle_detection_time (default 3.7s). + + Returns (elapsed_seconds, None) on success, (None, error_string) on + failure, so the caller can branch on the error explicitly instead of + ever mixing a message string into arithmetic. + """ + done = {'ok': False} + + def on_complete(fh): + # fh is a BytesIO on success, or None if the session was terminated + # (failure). cmd_get with a callback keeps the payload in memory, so we + # persist it here ourselves. + if fh is None: + return + try: + fh.seek(0) + with open(local, 'wb') as out: + out.write(fh.read()) + done['ok'] = True + except Exception as e: # noqa: BLE001 - surface write failures to the caller + report.info('local write failed: {}'.format(e)) + + ftp.cmd_get([remote], callback=on_complete) + + start = time.monotonic() + last_bytes = 0 + last_progress = start + next_hb = 0.0 + # process_ftp_reply timeout must exceed idle_detection_time; use a short + # slice and loop so we can enforce our own budget and stall detection. + slice_timeout = max(4.0, ftp.ftp_settings.idle_detection_time + 0.5) + while not done['ok']: + now = time.monotonic() + if now > next_hb: + send_heartbeat(mav) + next_hb = now + 1.0 + if now - start > FTP_BUDGET: + cur = ftp.read_total if ftp.read_total else last_bytes + return None, 'MAVFTP transfer stalled at {} bytes (budget {:.0f}s)'.format( + cur, FTP_BUDGET) + # drive one slice of the FTP state machine + ftp.process_ftp_reply('OpenFileRO', timeout=slice_timeout) + cur = ftp.read_total + if cur > last_bytes: + last_bytes = cur + last_progress = now + elif now - last_progress > 30.0 and not done['ok']: + # no forward progress for 30s and callback never fired + return None, 'MAVFTP transfer stalled at {} bytes (no progress 30s)'.format(cur) + # if the session ended without completing, process_ftp_reply keeps + # returning immediately on idle; break out via the budget/stall checks + elapsed = time.monotonic() - start + return elapsed, None + + +def main(): + parser = argparse.ArgumentParser( + description='Logger + MAVFTP download path test (v1.18 bench).') + add_connection_args(parser) + parser.add_argument('--log-duration', type=float, default=10, + help='seconds to log before stopping (default: %(default)s)') + parser.add_argument('--outdir', default='bench_reports', + help='base directory for the downloaded log (default: %(default)s)') + args = parser.parse_args() + + report = Reporter('mavftp_log') + + mav = None + try: + report.info('Connecting: {} @ {}'.format(args.connection, args.baudrate)) + try: + mav = connect(args.connection, baud=args.baudrate, timeout=args.connect_timeout) + except (TimeoutError, OSError) as e: + report.fail('connect', str(e)) + sys.exit(report.finish()) + + shell = MavlinkShell(mav) + if not shell.open(timeout=5): + report.fail('shell_open', 'nsh shell did not respond within 5s') + sys.exit(report.finish()) + + # logger status: confirm the module is running before we tell it to log + out, timed_out = shell.run('logger status', timeout=SHELL_TIMEOUT) + if timed_out: + report.fail('logger_status', '`logger status` stalled (no output in {:.0f}s)'.format( + SHELL_TIMEOUT)) + shell.close() + sys.exit(report.finish()) + low = out.lower() + if ('not running' in low or 'never' in low or + (low.strip() == '') or ('running' not in low and 'log' not in low)): + report.fail('logger_status', + 'logger module not running (check SDLOG_MODE): {}'.format(out.strip()[:200])) + shell.close() + sys.exit(report.finish()) + report.ok('logger_status', 'logger module running') + + out, timed_out = shell.run('logger on', timeout=SHELL_TIMEOUT) + if timed_out: + report.fail('logger_on', '`logger on` stalled') + shell.close() + sys.exit(report.finish()) + report.ok('logger_on', 'logging started') + + report.info('Logging for {}s'.format(args.log_duration)) + log_deadline = time.monotonic() + args.log_duration + while time.monotonic() < log_deadline: + # keep the link alive and the autopilot streaming during the wait + send_heartbeat(mav) + mav.recv_match(blocking=True, timeout=0.5) + + out, timed_out = shell.run('logger off', timeout=SHELL_TIMEOUT) + if timed_out: + report.fail('logger_off', '`logger off` stalled (flush not confirmed)') + shell.close() + sys.exit(report.finish()) + report.ok('logger_off', 'logging stopped and flushed') + shell.close() + # give the filesystem a moment to settle after the flush + time.sleep(1.0) + + # MAVFTP: find the newest log directory, then the newest .ulg in it + ftp = mavftp.MAVFTP(mav, target_system=mav.target_system, + target_component=mav.target_component) + + entries = ftp_list(ftp, LOG_ROOT) + dirs = sorted([e.name for e in entries if e.is_dir]) + if not dirs: + report.fail('ftp_list_root', + 'no log directories under {} (found: {})'.format( + LOG_ROOT, [e.name for e in entries])) + sys.exit(report.finish()) + newest_dir = dirs[-1] + report.ok('ftp_list_root', 'newest log dir: {}'.format(newest_dir)) + + log_dir = '{}/{}'.format(LOG_ROOT, newest_dir) + entries = ftp_list(ftp, log_dir) + ulgs = sorted([e for e in entries if not e.is_dir and e.name.endswith('.ulg')], + key=lambda e: e.name) + if not ulgs: + report.fail('ftp_list_dir', + 'no .ulg in {} (found: {})'.format( + log_dir, [e.name for e in entries])) + sys.exit(report.finish()) + newest = ulgs[-1] + report.ok('ftp_list_dir', 'newest ulg: {} ({} B reported)'.format( + newest.name, newest.size_b)) + + remote = '{}/{}'.format(log_dir, newest.name) + outdir = make_report_dir(args.outdir, 'mavftp_log') + local = os.path.join(outdir, newest.name) + + report.info('Downloading {} -> {}'.format(remote, local)) + elapsed, ftp_err = ftp_download(mav, ftp, remote, local, report) + if ftp_err is not None or elapsed is None: + report.fail('ftp_download', ftp_err if ftp_err else 'download failed') + sys.exit(report.finish()) + + if not os.path.exists(local): + report.fail('ftp_download', 'download reported complete but {} is missing'.format(local)) + sys.exit(report.finish()) + size = os.path.getsize(local) + rate = (size / 1024.0) / elapsed if elapsed > 0 else 0.0 + report.ok('ftp_download', '{} B in {:.2f}s ({:.1f} KB/s)'.format(size, elapsed, rate)) + + if size <= MIN_LOG_SIZE: + report.fail('log_size', 'downloaded file is only {} B (<= {} B)'.format(size, MIN_LOG_SIZE)) + sys.exit(report.finish()) + report.ok('log_size', '{} B'.format(size)) + + with open(local, 'rb') as f: + head = f.read(7) + if head != ULOG_MAGIC7: + report.fail('ulog_magic', + 'header {} does not match ULog magic {}'.format( + head.hex(), ULOG_MAGIC7.hex())) + sys.exit(report.finish()) + report.ok('ulog_magic', 'ULog magic bytes verified') + + # Optional deep parse with pyulog; degrade gracefully if unavailable. + try: + from pyulog import ULog + except ImportError: + report.info('pyulog not installed; skipping full parse ' + '(pip3 install --user pyulog for message counts)') + else: + try: + ulog = ULog(local) + msg_count = len(ulog.data_list) + report.ok('pyulog_parse', 'parsed {} logged message series'.format(msg_count)) + except Exception as e: # noqa: BLE001 - a parse failure is a real finding + report.fail('pyulog_parse', 'pyulog failed to parse the log: {}'.format(e)) + sys.exit(report.finish()) + finally: + if mav is not None: + try: + mav.close() + except Exception: # noqa: BLE001 - cleanup only + pass + + sys.exit(report.finish()) + + +if __name__ == '__main__': + main() diff --git a/Tools/bench_test/mission_torture.py b/Tools/bench_test/mission_torture.py new file mode 100755 index 00000000000..7cae6e11bb2 --- /dev/null +++ b/Tools/bench_test/mission_torture.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python3 +""" +Mission upload/download/clear torture test for on-bench PX4 hardware. + +v1.18 risk area: dataman and the mission shared-state path were reworked and +a brand-new mutex now guards mission shared state. A regression there shows +up as a SILENT HANG (a MISSION_REQUEST that never arrives, a MISSION_ACK that +never comes, a download that stalls mid-list) or as a corrupted round-trip. +This script repeatedly uploads a large mission, reads it back and compares it +item-by-item, then clears it, with a hard timeout on every wait so a stall +becomes a named FAIL naming the stalled step and the seq reached. + +With a second connection given, iterations alternate between the two links +(iteration parity picks the link) to exercise the new mission shared-state +mutex from two MAVLink channels. + +Mission protocol (verified in src/modules/mavlink/mavlink_mission.cpp): + upload: MISSION_COUNT -> per-item MISSION_REQUEST_INT / MISSION_REQUEST + -> we reply MISSION_ITEM_INT -> final MISSION_ACK(ACCEPTED) + download: MISSION_REQUEST_LIST -> MISSION_COUNT -> per-item + MISSION_REQUEST_INT -> we reply, then send MISSION_ACK(ACCEPTED) + clear: MISSION_CLEAR_ALL -> MISSION_ACK(ACCEPTED) + +Usage: + mission_torture.py CONNECTION [CONNECTION2] [-b BAUD] + [--baudrate2 BAUD2] [--iterations N] [--items K] +""" + +import argparse +import math +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import px4bench +from px4bench import mavutil + +DEFAULT_ITERATIONS = 10 +DEFAULT_ITEMS = 220 # <= smallest CONFIG_NUM_MISSION_ITMES_SUPPORTED (500) +DEFAULT_BAUD2 = 57600 + +MAV_CMD_NAV_WAYPOINT = mavutil.mavlink.MAV_CMD_NAV_WAYPOINT +MAV_FRAME = mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT +MAV_MISSION_TYPE_MISSION = mavutil.mavlink.MAV_MISSION_TYPE_MISSION +MAV_MISSION_ACCEPTED = mavutil.mavlink.MAV_MISSION_ACCEPTED + +BASE_LAT = 47.397742 +BASE_LON = 8.545594 + +# Per-message wait cap and per-iteration transaction deadline. +STEP_TIMEOUT_S = 5.0 +TRANSACTION_DEADLINE_S = 60.0 +COUNT_RETRANSMITS = 3 + + +def transaction_deadline(num_items): + """Transaction budget scaled for large missions on slow links. + + 220 items over a 57600 baud radio shared with telemetry streams can + legitimately take more than a minute; 0.5s per item is still tight + enough that a genuine stall (per-step 5s silence) fails much earlier. + """ + return max(TRANSACTION_DEADLINE_S, 0.5 * num_items) + +# Messages we care about; anything else (PARAM_VALUE, HEARTBEAT, ...) is drained. +UPLOAD_TYPES = ['MISSION_REQUEST_INT', 'MISSION_REQUEST', 'MISSION_ACK'] +DOWNLOAD_COUNT_TYPES = ['MISSION_COUNT', 'MISSION_ACK'] +DOWNLOAD_ITEM_TYPES = ['MISSION_ITEM_INT', 'MISSION_ITEM', 'MISSION_ACK'] + + +# --------------------------------------------------------------------------- +# Deterministic mission generation +# --------------------------------------------------------------------------- + +class Item: + """A single generated waypoint; comparison uses the fields we round-trip.""" + + def __init__(self, seq, lat_int, lon_int, alt, current): + self.seq = seq + self.command = MAV_CMD_NAV_WAYPOINT + self.frame = MAV_FRAME + self.current = current + self.autocontinue = 1 + self.param1 = 0.0 + self.param2 = 2.0 # acceptance radius + self.param3 = 0.0 + self.param4 = 0.0 + self.x = lat_int # int31, 1e-7 deg + self.y = lon_int + self.z = alt + + +def generate_mission(iteration, k): + """Deterministic mission of k items, keyed on (iteration, k).""" + items = [] + for seq in range(k): + lat_int = int((BASE_LAT + 0.0001 * seq) * 1e7) + iteration + lon_int = int((BASE_LON + 0.0001 * seq) * 1e7) + iteration + alt = 20.0 + (seq % 50) + items.append(Item(seq, lat_int, lon_int, alt, 1 if seq == 0 else 0)) + return items + + +# --------------------------------------------------------------------------- +# Upload +# --------------------------------------------------------------------------- + +def send_item(mav, item): + mav.mav.mission_item_int_send( + mav.target_system, mav.target_component, + item.seq, item.frame, item.command, + item.current, item.autocontinue, + item.param1, item.param2, item.param3, item.param4, + item.x, item.y, item.z, + MAV_MISSION_TYPE_MISSION) + + +def upload_mission(report, mav, items, iteration): + """Run the upload handshake. Returns (ok, duration, detail).""" + start = time.monotonic() + deadline = start + transaction_deadline(len(items)) + + mav.mav.mission_count_send( + mav.target_system, mav.target_component, + len(items), MAV_MISSION_TYPE_MISSION) + + count_retransmits = 0 + seq_reached = -1 + saw_any_request = False + + while time.monotonic() < deadline: + m = mav.recv_match(type=UPLOAD_TYPES, blocking=True, timeout=STEP_TIMEOUT_S) + + if m is None: + # Initial silence: our MISSION_COUNT may have been dropped; retry. + if not saw_any_request and count_retransmits < COUNT_RETRANSMITS: + count_retransmits += 1 + report.info('iter {}: no request, retransmitting MISSION_COUNT ' + '({}/{})'.format(iteration, count_retransmits, COUNT_RETRANSMITS)) + mav.mav.mission_count_send( + mav.target_system, mav.target_component, + len(items), MAV_MISSION_TYPE_MISSION) + continue + return (False, time.monotonic() - start, + 'upload stalled waiting for request/ack at seq {}'.format(seq_reached)) + + t = m.get_type() + + if t in ('MISSION_REQUEST_INT', 'MISSION_REQUEST'): + saw_any_request = True + seq = m.seq + # Respond to whatever seq is requested (handles dup / out-of-order). + if 0 <= seq < len(items): + send_item(mav, items[seq]) + seq_reached = max(seq_reached, seq) + else: + return (False, time.monotonic() - start, + 'autopilot requested out-of-range seq {} (have {})'.format( + seq, len(items))) + + elif t == 'MISSION_ACK': + ok = (m.type == MAV_MISSION_ACCEPTED) + detail = 'ACK type {} at seq {}'.format(m.type, seq_reached) + return ok, time.monotonic() - start, detail + + return (False, time.monotonic() - start, + 'upload transaction deadline {:.0f}s hit at seq {}'.format( + transaction_deadline(len(items)), seq_reached)) + + +# --------------------------------------------------------------------------- +# Download + compare +# --------------------------------------------------------------------------- + +def download_mission(mav): + """Request and collect the mission. Returns (items_or_None, duration, detail).""" + start = time.monotonic() + deadline = start + TRANSACTION_DEADLINE_S + + mav.mav.mission_request_list_send( + mav.target_system, mav.target_component, MAV_MISSION_TYPE_MISSION) + + # Wait for MISSION_COUNT. + count = None + while time.monotonic() < deadline: + m = mav.recv_match(type=DOWNLOAD_COUNT_TYPES, blocking=True, timeout=STEP_TIMEOUT_S) + if m is None: + return None, time.monotonic() - start, 'download stalled waiting for MISSION_COUNT' + t = m.get_type() + if t == 'MISSION_COUNT': + count = m.count + # extend the budget now that the item count is known + deadline = start + transaction_deadline(count) + break + if t == 'MISSION_ACK': + # An error ACK here means the request was rejected. + return None, time.monotonic() - start, 'got MISSION_ACK type {} instead of COUNT'.format(m.type) + + if count is None: + return None, time.monotonic() - start, 'download stalled before MISSION_COUNT' + + items = {} + next_seq = 0 + while next_seq < count and time.monotonic() < deadline: + mav.mav.mission_request_int_send( + mav.target_system, mav.target_component, next_seq, MAV_MISSION_TYPE_MISSION) + m = mav.recv_match(type=DOWNLOAD_ITEM_TYPES, blocking=True, timeout=STEP_TIMEOUT_S) + if m is None: + return None, time.monotonic() - start, \ + 'download stalled waiting for item seq {} of {}'.format(next_seq, count) + t = m.get_type() + if t in ('MISSION_ITEM_INT', 'MISSION_ITEM'): + items[m.seq] = m + if m.seq == next_seq: + next_seq += 1 + elif t == 'MISSION_ACK': + return None, time.monotonic() - start, \ + 'unexpected MISSION_ACK type {} at seq {}'.format(m.type, next_seq) + + if len(items) < count: + return None, time.monotonic() - start, \ + 'download incomplete: got {}/{} items'.format(len(items), count) + + # Terminate the download transaction with our own ACK. + mav.mav.mission_ack_send( + mav.target_system, mav.target_component, + MAV_MISSION_ACCEPTED, MAV_MISSION_TYPE_MISSION) + + ordered = [items[s] for s in range(count)] + return ordered, time.monotonic() - start, 'downloaded {} items'.format(count) + + +def compare_mission(expected, downloaded): + """Compare item-by-item. Returns (ok, detail with first differing seq).""" + if len(downloaded) != len(expected): + return False, 'count mismatch: expected {} got {}'.format( + len(expected), len(downloaded)) + + for exp, got in zip(expected, downloaded): + if got.seq != exp.seq: + return False, 'seq {}: seq field mismatch (got {})'.format(exp.seq, got.seq) + if got.command != exp.command: + return False, 'seq {}: command {} != {}'.format(exp.seq, got.command, exp.command) + if got.frame != exp.frame: + return False, 'seq {}: frame {} != {}'.format(exp.seq, got.frame, exp.frame) + if got.x != exp.x: + return False, 'seq {}: x {} != {}'.format(exp.seq, got.x, exp.x) + if got.y != exp.y: + return False, 'seq {}: y {} != {}'.format(exp.seq, got.y, exp.y) + if not math.isclose(got.z, exp.z, abs_tol=1e-3): + return False, 'seq {}: z {} != {} (tol 1e-3)'.format(exp.seq, got.z, exp.z) + + return True, 'all {} items match'.format(len(expected)) + + +# --------------------------------------------------------------------------- +# Clear +# --------------------------------------------------------------------------- + +def clear_mission(mav): + """MISSION_CLEAR_ALL -> MISSION_ACK(ACCEPTED). Returns (ok, detail).""" + deadline = time.monotonic() + TRANSACTION_DEADLINE_S + mav.mav.mission_clear_all_send( + mav.target_system, mav.target_component, MAV_MISSION_TYPE_MISSION) + while time.monotonic() < deadline: + m = mav.recv_match(type='MISSION_ACK', blocking=True, timeout=STEP_TIMEOUT_S) + if m is None: + return False, 'clear stalled waiting for MISSION_ACK' + if m.type == MAV_MISSION_ACCEPTED: + return True, 'cleared' + return False, 'clear rejected: MISSION_ACK type {}'.format(m.type) + return False, 'clear transaction deadline hit' + + +def verify_cleared(mav): + """After clear, MISSION_REQUEST_LIST should yield MISSION_COUNT == 0.""" + deadline = time.monotonic() + TRANSACTION_DEADLINE_S + mav.mav.mission_request_list_send( + mav.target_system, mav.target_component, MAV_MISSION_TYPE_MISSION) + while time.monotonic() < deadline: + m = mav.recv_match(type=DOWNLOAD_COUNT_TYPES, blocking=True, timeout=STEP_TIMEOUT_S) + if m is None: + return False, 'verify-clear stalled waiting for MISSION_COUNT' + t = m.get_type() + if t == 'MISSION_COUNT': + # Terminate the (empty) list transaction. + mav.mav.mission_ack_send( + mav.target_system, mav.target_component, + MAV_MISSION_ACCEPTED, MAV_MISSION_TYPE_MISSION) + if m.count == 0: + return True, 'count 0 after clear' + return False, 'count {} after clear (expected 0)'.format(m.count) + if t == 'MISSION_ACK': + # Empty mission may be reported via ACK; treat non-error as cleared. + if m.type == MAV_MISSION_ACCEPTED: + return True, 'empty mission (ACK) after clear' + return False, 'verify-clear got MISSION_ACK type {}'.format(m.type) + return False, 'verify-clear transaction deadline hit' + + +# --------------------------------------------------------------------------- +# main +# --------------------------------------------------------------------------- + +def run_iteration(report, mav, iteration, items_k, link_label): + """One full upload/download/compare/clear cycle. Returns True on full pass.""" + expected = generate_mission(iteration, items_k) + + up_ok, up_dur, up_detail = upload_mission(report, mav, expected, iteration) + if not report.check('iter{}_upload'.format(iteration), up_ok, + '[{}] {} ({:.1f}s)'.format(link_label, up_detail, up_dur)): + return False + + downloaded, dl_dur, dl_detail = download_mission(mav) + if downloaded is None: + report.fail('iter{}_download'.format(iteration), + '[{}] {} ({:.1f}s)'.format(link_label, dl_detail, dl_dur)) + return False + + cmp_ok, cmp_detail = compare_mission(expected, downloaded) + if not report.check('iter{}_compare'.format(iteration), cmp_ok, + '[{}] {}'.format(link_label, cmp_detail)): + return False + + clr_ok, clr_detail = clear_mission(mav) + if not report.check('iter{}_clear'.format(iteration), clr_ok, + '[{}] {}'.format(link_label, clr_detail)): + return False + + vfy_ok, vfy_detail = verify_cleared(mav) + report.check('iter{}_verify_clear'.format(iteration), vfy_ok, + '[{}] {}'.format(link_label, vfy_detail)) + + if up_ok and downloaded is not None and cmp_ok and clr_ok and vfy_ok: + report.info('iter {} PASS [{}] upload {:.1f}s download {:.1f}s'.format( + iteration, link_label, up_dur, dl_dur)) + return True + return False + + +def main(): + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + px4bench.add_connection_args(parser, dual_link=True) + parser.add_argument('--baudrate2', type=int, default=DEFAULT_BAUD2, + help='baud rate for the second connection (default: %(default)s)') + parser.add_argument('--iterations', type=int, default=DEFAULT_ITERATIONS, + help='upload/download/clear iterations (default: %(default)s)') + parser.add_argument('--items', type=int, default=DEFAULT_ITEMS, + help='mission items per iteration (default: %(default)s)') + args = parser.parse_args() + + report = px4bench.Reporter('mission_torture') + + try: + mav1 = px4bench.connect(args.connection, baud=args.baudrate, + timeout=args.connect_timeout) + except (TimeoutError, OSError) as e: + report.fail('connect', 'link 1 {}: {}'.format(args.connection, e)) + sys.exit(report.finish()) + report.info('link 1 connected to system {} component {}'.format( + mav1.target_system, mav1.target_component)) + + mav2 = None + if args.connection2: + try: + mav2 = px4bench.connect(args.connection2, baud=args.baudrate2, + timeout=args.connect_timeout) + report.info('link 2 connected to system {} component {}'.format( + mav2.target_system, mav2.target_component)) + except (TimeoutError, OSError) as e: + report.fail('connect', 'link 2 {}: {}'.format(args.connection2, e)) + sys.exit(report.finish()) + + try: + for iteration in range(args.iterations): + if mav2 is not None and (iteration % 2 == 1): + mav, label = mav2, 'link2' + else: + mav, label = mav1, 'link1' + run_iteration(report, mav, iteration, args.items, label) + finally: + for m in (mav1, mav2): + try: + if m is not None: + m.close() + except Exception: + pass + + sys.exit(report.finish()) + + +if __name__ == '__main__': + main() diff --git a/Tools/bench_test/param_torture.py b/Tools/bench_test/param_torture.py new file mode 100755 index 00000000000..331d5374550 --- /dev/null +++ b/Tools/bench_test/param_torture.py @@ -0,0 +1,403 @@ +#!/usr/bin/env python3 +""" +Parameter-subsystem torture test for on-bench PX4 hardware. + +v1.18 risk area: the parameters backend received a concurrency and locking +rework. A regression there shows up as a SILENT HANG (a PARAM_VALUE that +never arrives, a full download that stalls halfway) or as a dropped write +that only surfaces after a reboot. This script hammers the parameter +protocol over MAVLink with hard timeouts on every wait, so a stall becomes +a named FAIL instead of a hung process. + +Three phases: + 1. Full parameter download (PARAM_REQUEST_LIST), stall-detected. + 2. Set / readback loop on a harmless scratch parameter. + 3. Persistence across a reboot (skippable with --skip-reboot). + +The scratch parameter (SDLOG_UTC_OFFSET) only shifts log-file naming +timestamps, so it is safe to thrash on a bench. Its original value is +always restored while a connection is alive, even on failure. + +Usage: + param_torture.py CONNECTION [-b BAUD] [--iterations N] + [--param NAME] [--skip-reboot] +""" + +import argparse +import os +import struct +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import px4bench +from px4bench import mavutil + +DEFAULT_PARAM = 'SDLOG_UTC_OFFSET' +DEFAULT_ITERATIONS = 50 + +# Persistence-phase marker value (within SDLOG_UTC_OFFSET min/max -1000..1000). +MARKER_VALUE = 777 + +MAV_PARAM_TYPE_INT32 = mavutil.mavlink.MAV_PARAM_TYPE_INT32 + +# Download stall thresholds. +DOWNLOAD_STALL_S = 10.0 # FAIL if no new param index for this long +DOWNLOAD_OVERALL_CAP_S = 180.0 + +# Per-message wait timeouts. +SET_ECHO_TIMEOUT_S = 5.0 +READ_TIMEOUT_S = 5.0 + + +# --------------------------------------------------------------------------- +# INT32 <-> float union (byte-wise) encoding. +# +# PX4 transports an INT32 parameter as the raw bit pattern of the int placed +# into the float param_value field. To send: pack the int as ' (name, int32_value) + by_name = {} # name -> int32_value + advertised = None + start = time.monotonic() + last_new = start + + while True: + now = time.monotonic() + if now - start > DOWNLOAD_OVERALL_CAP_S: + report.fail('param_download', + 'overall cap {:.0f}s hit with {}/{} params'.format( + DOWNLOAD_OVERALL_CAP_S, len(received), + advertised if advertised is not None else '?')) + return by_name + if now - last_new > DOWNLOAD_STALL_S: + report.fail('param_download', + 'stalled: no new param for {:.0f}s at {}/{}'.format( + DOWNLOAD_STALL_S, len(received), + advertised if advertised is not None else '?')) + break + + m = mav.recv_match(type='PARAM_VALUE', blocking=True, timeout=1.0) + if m is None: + continue + + if advertised is None: + advertised = m.param_count + idx = m.param_index + name = param_id_str(m.param_id) + if idx not in received: + last_new = now + received[idx] = (name, param_float_to_int32(m.param_value)) + by_name[name] = param_float_to_int32(m.param_value) + + if advertised is not None and len(received) >= advertised: + break + + duration = time.monotonic() - start + + if advertised is None: + report.fail('param_download', 'no PARAM_VALUE received at all') + return by_name + + # Retry any missing indices once via PARAM_REQUEST_READ before failing. + if len(received) < advertised: + missing = [i for i in range(advertised) if i not in received] + report.info('retrying {} missing param indices once'.format(len(missing))) + for idx in missing: + mav.mav.param_request_read_send( + mav.target_system, mav.target_component, b'', idx) + deadline = time.monotonic() + 2.0 + while time.monotonic() < deadline: + m = mav.recv_match(type='PARAM_VALUE', blocking=True, timeout=0.5) + if m is None: + continue + r_idx = m.param_index + name = param_id_str(m.param_id) + received[r_idx] = (name, param_float_to_int32(m.param_value)) + by_name[name] = param_float_to_int32(m.param_value) + if r_idx == idx: + break + + report.check('param_download', + len(received) >= advertised, + 'received {}/{} params in {:.1f}s'.format( + len(received), advertised, duration)) + return by_name + + +# --------------------------------------------------------------------------- +# Phase 2: set / readback loop +# --------------------------------------------------------------------------- + +def phase_set_readback(report, mav, param, iterations): + """Loop set/readback with a value that changes every iteration. + + value_i = ((i * 37) % 1999) - 999 (stays within -1000..1000). + Individual failures are counted but the loop continues. + """ + report.info('Phase 2: set/readback loop, {} iterations'.format(iterations)) + echo_failures = 0 + read_failures = 0 + mismatch_failures = 0 + + for i in range(iterations): + value = ((i * 37) % 1999) - 999 + + set_param_int32(mav, param, value) + echo = wait_param_echo(mav, param, SET_ECHO_TIMEOUT_S) + if echo is None: + report.fail('param_set_echo', + 'set iteration {}: no PARAM_VALUE echo'.format(i)) + echo_failures += 1 + continue + if echo != value: + report.fail('param_set_echo', + 'set iteration {}: echo {} != set {}'.format(i, echo, value)) + echo_failures += 1 + # keep going: still try to read back + + readback, _ = read_param(mav, param, READ_TIMEOUT_S) + if readback is None: + report.fail('param_readback', + 'set iteration {}: no PARAM_VALUE on readback'.format(i)) + read_failures += 1 + continue + if readback != value: + report.fail('param_readback', + 'set iteration {}: readback {} != set {}'.format( + i, readback, value)) + mismatch_failures += 1 + + if (i + 1) % 10 == 0: + report.info(' {}/{} iterations done'.format(i + 1, iterations)) + + report.check('param_set_readback_loop', + echo_failures == 0 and read_failures == 0 and mismatch_failures == 0, + '{} iterations: {} echo, {} read, {} mismatch failures'.format( + iterations, echo_failures, read_failures, mismatch_failures)) + + +# --------------------------------------------------------------------------- +# Phase 3: persistence across reboot +# --------------------------------------------------------------------------- + +def phase_persistence(report, mav, param, conn_str, baud, original_value): + """Write a marker, save, reboot, verify it survived, then restore. + + Returns the (possibly new) mavutil connection so the caller can keep the + restore-in-finally path alive. + """ + report.info('Phase 3: persistence across reboot') + + set_param_int32(mav, param, MARKER_VALUE) + echo = wait_param_echo(mav, param, SET_ECHO_TIMEOUT_S) + if echo != MARKER_VALUE: + report.fail('persistence_set', + 'marker set echo {} != {}'.format(echo, MARKER_VALUE)) + return mav + + # Force an explicit flush to storage before we pull the power. + shell = px4bench.MavlinkShell(mav) + if not shell.open(timeout=5): + report.fail('persistence_shell', 'could not open nsh shell for param save') + return mav + out, timed_out = shell.run('param save', timeout=10) + shell.close() + if timed_out: + report.fail('persistence_save', + "'param save' did not complete within 10s (stalled)") + return mav + report.info("'param save' output: {}".format(out.strip() or '(none)')) + + try: + newmav, elapsed = px4bench.reboot_and_reconnect(mav, conn_str, baud, timeout=60) + except TimeoutError as e: + report.fail('persistence_reboot', str(e)) + return mav + report.info('rebooted and reconnected in {:.1f}s'.format(elapsed)) + mav = newmav + + survived, _ = read_param(mav, param, READ_TIMEOUT_S) + if survived is None: + report.fail('persistence_readback', + 'no PARAM_VALUE for {} after reboot (stalled)'.format(param)) + else: + report.check('persistence', + survived == MARKER_VALUE, + 'after reboot {} = {} (expected {})'.format( + param, survived, MARKER_VALUE)) + + # Restore original inside this phase too, then verify. + set_param_int32(mav, param, original_value) + echo = wait_param_echo(mav, param, SET_ECHO_TIMEOUT_S) + report.check('persistence_restore', + echo == original_value, + 'restored {} to {} (echo {})'.format(param, original_value, echo)) + return mav + + +# --------------------------------------------------------------------------- +# main +# --------------------------------------------------------------------------- + +def main(): + parser = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + px4bench.add_connection_args(parser) + parser.add_argument('--iterations', type=int, default=DEFAULT_ITERATIONS, + help='set/readback iterations (default: %(default)s)') + parser.add_argument('--param', default=DEFAULT_PARAM, + help='scratch parameter to thrash (default: %(default)s)') + parser.add_argument('--skip-reboot', action='store_true', + help='skip the reboot persistence phase') + args = parser.parse_args() + + report = px4bench.Reporter('param_torture') + + try: + mav = px4bench.connect(args.connection, baud=args.baudrate, + timeout=args.connect_timeout) + except (TimeoutError, OSError) as e: + report.fail('connect', str(e)) + sys.exit(report.finish()) + + report.info('connected to system {} component {}'.format( + mav.target_system, mav.target_component)) + + original_value = None + + try: + by_name = phase_full_download(report, mav) + + # Guard: a typo must not silently thrash the wrong (or no) param. + if args.param not in by_name: + report.fail('param_exists', + '{} not found in downloaded set; aborting before any set'.format( + args.param)) + sys.exit(report.finish()) + + original_value, _ = read_param(mav, args.param, READ_TIMEOUT_S) + if original_value is None: + report.fail('param_original', + 'could not read original value of {}'.format(args.param)) + sys.exit(report.finish()) + report.info('original {} = {}'.format(args.param, original_value)) + + phase_set_readback(report, mav, args.param, args.iterations) + + if args.skip_reboot: + report.info('Phase 3 skipped (--skip-reboot)') + else: + mav = phase_persistence(report, mav, args.param, args.connection, + args.baudrate, original_value) + + finally: + # Always restore the original value while a connection is alive. + if original_value is not None and mav is not None: + try: + set_param_int32(mav, args.param, original_value) + echo = wait_param_echo(mav, args.param, SET_ECHO_TIMEOUT_S) + report.check('final_restore', + echo == original_value, + 'restored {} to {} (echo {})'.format( + args.param, original_value, echo)) + except Exception as e: + report.fail('final_restore', + 'exception while restoring {}: {}'.format(args.param, e)) + try: + if mav is not None: + mav.close() + except Exception: + pass + + sys.exit(report.finish()) + + +if __name__ == '__main__': + main() diff --git a/Tools/bench_test/px4bench.py b/Tools/bench_test/px4bench.py new file mode 100644 index 00000000000..10867d2bc52 --- /dev/null +++ b/Tools/bench_test/px4bench.py @@ -0,0 +1,344 @@ +#!/usr/bin/env python3 +""" +Shared helpers for the PX4 bench-test suite (Tools/bench_test). + +Provides MAVLink connection setup, a non-interactive nsh shell over +SERIAL_CONTROL (reusing the pattern from Tools/mavlink_shell.py), reboot +and USB re-detection helpers, and PASS/FAIL reporting. + +Every operation takes a timeout: a hung board is a finding, not an excuse +for a hung test script. +""" + +import glob +import os +import re +import sys +import time +from datetime import datetime, timezone + +PYMAVLINK_INSTALL_HINT = """\ +Failed to import pymavlink: {err} + +Install it with: + pip3 install --user pymavlink +""" + +try: + from pymavlink import mavutil +except ImportError as e: + print(PYMAVLINK_INSTALL_HINT.format(err=e)) + sys.exit(2) + +SERIAL_CONTROL_DEV_SHELL = 10 # SERIAL_CONTROL_DEV_SHELL (see Tools/mavlink_shell.py) +DEFAULT_BAUD = 57600 +USB_DEVICE_GLOB_DARWIN = '/dev/tty.usbmodem*' +USB_DEVICE_GLOB_LINUX = '/dev/serial/by-id/*PX4*' + + +# --------------------------------------------------------------------------- +# Reporting +# --------------------------------------------------------------------------- + +class Reporter: + """Collects named PASS/FAIL checks and prints a summary. + + Usage: + report = Reporter('boot_health') + report.check('heartbeat', ok, 'detail string') + ... + sys.exit(report.finish()) + """ + + def __init__(self, test_name): + self.test_name = test_name + self.results = [] # (name, ok, detail) + self.start_time = time.monotonic() + + def check(self, name, ok, detail=''): + tag = 'PASS' if ok else 'FAIL' + msg = '[{}] {}: {}'.format(tag, name, detail) if detail else '[{}] {}'.format(tag, name) + print(msg, flush=True) + self.results.append((name, bool(ok), detail)) + return bool(ok) + + def fail(self, name, detail=''): + return self.check(name, False, detail) + + def ok(self, name, detail=''): + return self.check(name, True, detail) + + def info(self, msg): + print('[INFO] {}'.format(msg), flush=True) + + @property + def num_failed(self): + return sum(1 for _, ok, _ in self.results if not ok) + + def finish(self): + """Print summary, return process exit code (0 = all passed).""" + elapsed = time.monotonic() - self.start_time + total = len(self.results) + failed = self.num_failed + print('-' * 60) + if failed == 0: + print('{}: PASS ({} checks, {:.1f}s)'.format(self.test_name, total, elapsed)) + else: + print('{}: FAIL ({}/{} checks failed, {:.1f}s)'.format( + self.test_name, failed, total, elapsed)) + for name, ok, detail in self.results: + if not ok: + print(' FAILED: {}{}'.format(name, ' - ' + detail if detail else '')) + return 0 if failed == 0 else 1 + + +def make_report_dir(base='bench_reports', test_name=''): + """Create and return a timestamped report directory.""" + stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ') + path = os.path.join(base, '{}_{}'.format(stamp, test_name) if test_name else stamp) + os.makedirs(path, exist_ok=True) + return path + + +# --------------------------------------------------------------------------- +# Connection +# --------------------------------------------------------------------------- + +def is_serial_device(conn_str): + return conn_str.startswith('/dev/') or conn_str.upper().startswith('COM') + + +def connect(conn_str, baud=DEFAULT_BAUD, timeout: float = 20, source_system=254): + """Open a MAVLink connection and wait for a heartbeat from the autopilot. + + Returns the mavutil connection, or raises TimeoutError/OSError. + """ + mav = mavutil.mavlink_connection(conn_str, baud=baud, autoreconnect=False, + source_system=source_system, + source_component=mavutil.mavlink.MAV_COMP_ID_MISSIONPLANNER) + assert isinstance(mav, mavutil.mavfile), 'unexpected connection type for {}'.format(conn_str) + # announce ourselves so the autopilot streams to us + mav.mav.heartbeat_send(mavutil.mavlink.MAV_TYPE_GCS, + mavutil.mavlink.MAV_AUTOPILOT_INVALID, 0, 0, 0) + hb = mav.wait_heartbeat(timeout=int(timeout)) + if hb is None: + mav.close() + raise TimeoutError('no HEARTBEAT on {} within {}s'.format(conn_str, timeout)) + return mav + + +def wait_heartbeat(mav, timeout: float = 10): + """Wait for the next autopilot heartbeat. Returns the message or None.""" + return mav.wait_heartbeat(timeout=int(timeout)) + + +def drain(mav, duration=0.5): + """Read and discard pending messages for a short window.""" + deadline = time.monotonic() + duration + while time.monotonic() < deadline: + if mav.recv_match(blocking=True, timeout=0.05) is None: + pass + + +# --------------------------------------------------------------------------- +# nsh shell over MAVLink SERIAL_CONTROL +# --------------------------------------------------------------------------- + +class MavlinkShell: + """Non-interactive nsh shell over SERIAL_CONTROL (dev 10). + + Write pattern follows Tools/mavlink_shell.py; completion detection uses + the sentinel-echo trick from Tools/HIL/run_nsh_cmd.py: + ; echo + so we know when output for is complete without relying on prompt + parsing. + """ + + def __init__(self, mav): + self.mav = mav + self.buf = '' + self._next_heartbeat = 0.0 + self._seq = 0 + + def _write(self, text): + b = text + while len(b) > 0: + n = min(len(b), 70) + buf = [ord(c) for c in b[:n]] + buf.extend([0] * (70 - len(buf))) + self.mav.mav.serial_control_send( + SERIAL_CONTROL_DEV_SHELL, + mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE | + mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND, + 0, 0, n, buf) + b = b[n:] + + def _pump(self, window=0.03): + """Read pending SERIAL_CONTROL data into self.buf, keep heartbeats going.""" + now = time.monotonic() + if now > self._next_heartbeat: + self.mav.mav.heartbeat_send(mavutil.mavlink.MAV_TYPE_GCS, + mavutil.mavlink.MAV_AUTOPILOT_INVALID, 0, 0, 0) + self._next_heartbeat = now + 1.0 + m = self.mav.recv_match(condition='SERIAL_CONTROL.count!=0', + type='SERIAL_CONTROL', blocking=True, timeout=window) + if m is not None: + self.buf += ''.join(chr(x) for x in m.data[:m.count]) + + def open(self, timeout: float = 5): + """Wake the shell; returns True if any shell output is seen.""" + self._write('\n') + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + self._pump() + if 'nsh>' in self.buf or len(self.buf) > 0: + self.buf = '' + return True + return False + + def run(self, cmd, timeout: float = 10): + """Run one command, return (output_str, timed_out_bool). + + On timeout the partial output is returned and timed_out is True -- + a command that never completes is exactly the hang we are hunting. + """ + self._seq += 1 + sentinel = 'BENCHDONE{}'.format(self._seq) + self.buf = '' + # two echos like run_nsh_cmd.py, in case the first line is garbled + self._write('{}; echo {}; echo {}\n'.format(cmd, sentinel, sentinel)) + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + self._pump() + # sentinel on its own line (not the command echo containing "echo ") + if re.search(r'^{}\s*$'.format(re.escape(sentinel)), self.buf, re.MULTILINE): + return self._strip(cmd, sentinel), False + return self._strip(cmd, sentinel), True + + def _strip(self, cmd, sentinel): + """Remove command echo and sentinel lines from captured output.""" + lines = [] + for line in self.buf.splitlines(): + if sentinel in line: + continue + if cmd in line and 'echo' in line: + continue + lines.append(line) + return '\n'.join(lines).strip() + + def close(self): + try: + self.mav.mav.serial_control_send(SERIAL_CONTROL_DEV_SHELL, 0, 0, 0, 0, [0] * 70) + except Exception: + pass + + +# --------------------------------------------------------------------------- +# Reboot / device replug helpers +# --------------------------------------------------------------------------- + +def send_reboot(mav): + """Request an autopilot reboot (MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, param1=1).""" + mav.mav.command_long_send( + mav.target_system, mav.target_component, + mavutil.mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0, + 1, 0, 0, 0, 0, 0, 0) + + +def list_usb_devices(pattern=None): + """List candidate PX4 USB serial devices.""" + if pattern: + return sorted(glob.glob(pattern)) + devs = sorted(glob.glob(USB_DEVICE_GLOB_DARWIN)) + if not devs: + devs = sorted(glob.glob(USB_DEVICE_GLOB_LINUX)) + if not devs: + devs = sorted(glob.glob('/dev/ttyACM*')) + return devs + + +def wait_device_gone(device, timeout=30): + """Wait until the serial device node disappears. Returns elapsed or None.""" + start = time.monotonic() + while time.monotonic() - start < timeout: + if not os.path.exists(device): + return time.monotonic() - start + time.sleep(0.2) + return None + + +def wait_device_back(device, timeout=45, pattern=None): + """Wait until the device node (or a matching one) reappears. + + USB enumeration can change the node name (usbmodem01 -> usbmodem101 on + macOS), so if the exact node does not come back we fall back to a glob + for the same device family. Returns (device_path, elapsed) or (None, None). + """ + if pattern is None: + base = re.sub(r'\d+$', '', device) + pattern = base + '*' if base != device else None + start = time.monotonic() + while time.monotonic() - start < timeout: + if os.path.exists(device): + return device, time.monotonic() - start + if pattern: + found = sorted(glob.glob(pattern)) + if found: + return found[0], time.monotonic() - start + time.sleep(0.2) + return None, None + + +def reboot_and_reconnect(mav, conn_str, baud=DEFAULT_BAUD, timeout=60): + """Reboot the autopilot and reconnect. + + Returns (new_mav_connection, elapsed_seconds). + Raises TimeoutError with a description of what stalled. + """ + start = time.monotonic() + send_reboot(mav) + time.sleep(0.5) + mav.close() + + if is_serial_device(conn_str): + gone = wait_device_gone(conn_str, timeout=15) + # Some boards re-enumerate too fast to observe the node vanish; that is fine. + newdev, _ = wait_device_back(conn_str, timeout=timeout) + if newdev is None: + raise TimeoutError('serial device {} did not come back within {}s ' + '(gone after {})'.format( + conn_str, timeout, + '{:.1f}s'.format(gone) if gone is not None else 'n/a')) + conn_str = newdev + time.sleep(2.0) # let the CDC ACM interface settle + else: + time.sleep(3.0) + + remaining = max(5.0, timeout - (time.monotonic() - start)) + last_err = None + while time.monotonic() - start < timeout: + try: + newmav = connect(conn_str, baud=baud, timeout=int(max(1, min(10, remaining)))) + return newmav, time.monotonic() - start + except (TimeoutError, OSError) as e: + last_err = e + time.sleep(1.0) + raise TimeoutError('no heartbeat after reboot within {}s (last error: {})'.format( + timeout, last_err)) + + +# --------------------------------------------------------------------------- +# Common CLI plumbing +# --------------------------------------------------------------------------- + +def add_connection_args(parser, dual_link=False): + parser.add_argument('connection', + help='MAVLink connection: serial device (/dev/tty.usbmodem01), ' + 'udp:IP:PORT, or tcp:IP:PORT') + if dual_link: + parser.add_argument('connection2', nargs='?', default=None, + help='optional second MAVLink connection (telemetry radio)') + parser.add_argument('--baudrate', '-b', type=int, default=DEFAULT_BAUD, + help='serial baud rate (default: %(default)s)') + parser.add_argument('--connect-timeout', type=float, default=20, + help='seconds to wait for the first heartbeat (default: %(default)s)') diff --git a/Tools/bench_test/reboot_loop.py b/Tools/bench_test/reboot_loop.py new file mode 100755 index 00000000000..a71238f6f49 --- /dev/null +++ b/Tools/bench_test/reboot_loop.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +""" +Reboot torture test for a PX4 board on real NuttX hardware. + +The v1.18 concurrency and locking rework changed startup ordering and shared +state teardown, so the risk is a board that boots fine once but occasionally +hangs on reboot, or comes back with a shell that never responds. This script +reboots the board in a loop and, after each reboot, proves the system is alive +two ways: a fresh MAVLink heartbeat and an nsh command (`free`) that actually +completes over SERIAL_CONTROL. + +Every reconnect has a hard timeout. If a cycle does not come back, we do not +hang: we report the cycle as FAIL naming what stalled, abort the remaining +cycles (the board is gone, nothing to gain by waiting again), print the +summary, and exit non-zero. +""" + +import argparse +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import px4bench + + +def main(): + parser = argparse.ArgumentParser( + description='PX4 reboot torture test: reboot N times, prove liveness each cycle.') + px4bench.add_connection_args(parser) + parser.add_argument('--iterations', type=int, default=10, + help='number of reboot cycles (default: %(default)s)') + parser.add_argument('--cycle-timeout', type=float, default=60, + help='seconds to allow per reboot+reconnect cycle (default: %(default)s)') + args = parser.parse_args() + + report = px4bench.Reporter('reboot_loop') + + try: + mav = px4bench.connect(args.connection, baud=args.baudrate, + timeout=args.connect_timeout) + except (TimeoutError, OSError) as e: + report.fail('initial connect', str(e)) + sys.exit(report.finish()) + report.ok('initial connect', 'heartbeat from {}'.format(args.connection)) + + conn_str = args.connection + for i in range(1, args.iterations + 1): + try: + newmav, elapsed = px4bench.reboot_and_reconnect( + mav, conn_str, baud=args.baudrate, timeout=args.cycle_timeout) + except TimeoutError as e: + report.fail('cycle {}'.format(i), str(e)) + report.info('board did not return; aborting remaining {} cycle(s)'.format( + args.iterations - i)) + sys.exit(report.finish()) + + mav = newmav + + # confirm a live heartbeat after reconnect + hb = px4bench.wait_heartbeat(mav, timeout=5) + if hb is None: + report.fail('cycle {} heartbeat'.format(i), + 'reconnected but no heartbeat within 5s') + report.info('aborting remaining {} cycle(s)'.format(args.iterations - i)) + sys.exit(report.finish()) + + # prove the shell (and thus the running system) is responsive + shell = px4bench.MavlinkShell(mav) + if not shell.open(timeout=5): + report.fail('cycle {} shell'.format(i), + 'no nsh output on SERIAL_CONTROL within 5s') + shell.close() + report.info('aborting remaining {} cycle(s)'.format(args.iterations - i)) + sys.exit(report.finish()) + + _, timed_out = shell.run('free', timeout=10) + shell.close() + if timed_out: + report.fail('cycle {}'.format(i), + 'shell command free stalled (no completion within 10s)') + report.info('aborting remaining {} cycle(s)'.format(args.iterations - i)) + sys.exit(report.finish()) + + report.ok('cycle {}'.format(i), + 'reconnected in {:.1f}s, shell responsive'.format(elapsed)) + + mav.close() + sys.exit(report.finish()) + + +if __name__ == '__main__': + main() diff --git a/Tools/bench_test/run_bench_suite.py b/Tools/bench_test/run_bench_suite.py new file mode 100755 index 00000000000..55e3c12c64d --- /dev/null +++ b/Tools/bench_test/run_bench_suite.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +""" +Orchestrator for the non-interactive PX4 v1.18 bench-test suite. + +Runs the individual bench tests in sequence against a board on the bench, +each as its own subprocess so a hang in one test cannot wedge the whole +run. The suite exists to qualify v1.18 on real NuttX hardware after the +mavlink locking rework; the individual tests exercise boot, parameter and +mission traffic, the logger + MAVFTP path, reboot recovery, and (when a +second link is given) the dual-link nested-send lock stress. + +Each test enforces its own timeouts, and this orchestrator wraps each in a +--per-test-timeout so even a fully wedged child is killed and recorded as a +FAIL naming what hung. usb_replug is interactive and is never run here. +""" + +import argparse +import os +import signal +import subprocess +import sys +import time + + +# Test order for the suite. dual_link_forwarding is inserted after +# mission_torture only when a second connection is provided. +BASE_SEQUENCE = [ + 'boot_health', + 'param_torture', + 'mission_torture', + 'mavftp_log', + 'reboot_loop', +] +DUAL_LINK_TEST = 'dual_link_forwarding' +DUAL_LINK_AFTER = 'mission_torture' + + +def script_path(name): + here = os.path.dirname(os.path.abspath(__file__)) + return os.path.join(here, name + '.py') + + +def build_argv(name, args): + """Build the argv for one test's subprocess, per each test's own CLI.""" + argv = [sys.executable, script_path(name), args.connection] + + # tests that take a second positional connection + if name in ('mission_torture', DUAL_LINK_TEST): + if args.connection2: + argv.append(args.connection2) + + # baud rate is accepted by every test + argv += ['-b', str(args.baudrate)] + + # per-test extra flags + if name == 'boot_health': + argv += ['--report-dir', args.report_dir] + elif name == 'mavftp_log': + argv += ['--outdir', args.report_dir] + + return argv + + +def run_one(name, args): + """Run one test as a subprocess with inherited stdout/stderr so its output + streams live. Enforces --per-test-timeout; on expiry kills the whole + process group. Returns (status, duration_seconds, detail). + """ + argv = build_argv(name, args) + print('=' * 70, flush=True) + print('RUN {}: {}'.format(name, ' '.join(argv)), flush=True) + print('=' * 70, flush=True) + + start = time.monotonic() + # start_new_session so the child gets its own process group; if it hangs we + # can kill the whole group (a wedged test may have spawned threads/children). + try: + proc = subprocess.Popen(argv, start_new_session=True) + except OSError as e: + return 'FAIL', 0.0, 'could not launch: {}'.format(e) + + try: + rc = proc.wait(timeout=args.per_test_timeout) + except subprocess.TimeoutExpired: + # kill the whole process group, escalate to SIGKILL if needed + try: + os.killpg(os.getpgid(proc.pid), signal.SIGTERM) + except OSError: + pass + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + try: + os.killpg(os.getpgid(proc.pid), signal.SIGKILL) + except OSError: + pass + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + pass + dur = time.monotonic() - start + return 'FAIL', dur, '{} hung (killed after {:.0f}s)'.format(name, args.per_test_timeout) + + dur = time.monotonic() - start + if rc == 0: + return 'PASS', dur, '' + return 'FAIL', dur, 'exit code {}'.format(rc) + + +def main(): + parser = argparse.ArgumentParser( + description='Run the non-interactive PX4 v1.18 bench-test suite.') + parser.add_argument('connection', + help='MAVLink connection: serial device, udp:IP:PORT, or tcp:IP:PORT') + parser.add_argument('connection2', nargs='?', default=None, + help='optional second connection; enables dual_link_forwarding ' + 'and is passed to mission_torture') + parser.add_argument('--baudrate', '-b', type=int, default=57600, + help='serial baud rate (default: %(default)s)') + parser.add_argument('--skip', default='', + help='comma-separated list of test names to skip') + parser.add_argument('--report-dir', default='bench_reports', + help='base directory for reports (default: %(default)s)') + parser.add_argument('--per-test-timeout', type=float, default=900, + help='seconds before a test is killed as hung (default: %(default)s)') + parser.add_argument('--stop-on-fail', action='store_true', default=False, + help='stop the suite at the first failing test') + args = parser.parse_args() + + skip = {s.strip() for s in args.skip.split(',') if s.strip()} + + # build the run sequence + sequence = [] + for name in BASE_SEQUENCE: + sequence.append(name) + if name == DUAL_LINK_AFTER and args.connection2: + sequence.append(DUAL_LINK_TEST) + + print('PX4 bench-test suite') + print(' connection : {}'.format(args.connection)) + print(' connection2: {}'.format(args.connection2 if args.connection2 else '(none)')) + print(' sequence : {}'.format(', '.join(sequence))) + if skip: + print(' skipping : {}'.format(', '.join(sorted(skip)))) + print(' NOTE: usb_replug is interactive and is not run by this suite; ' + 'run it manually.') + print() + + results = [] # (name, status, duration, detail) + for name in sequence: + if name in skip: + results.append((name, 'SKIP', 0.0, 'skipped via --skip')) + print('SKIP {}'.format(name), flush=True) + continue + status, dur, detail = run_one(name, args) + results.append((name, status, dur, detail)) + print('--> {} {} ({:.1f}s){}'.format( + name, status, dur, ' - ' + detail if detail else ''), flush=True) + if status == 'FAIL' and args.stop_on_fail: + print('stop-on-fail set; halting suite after {}'.format(name), flush=True) + break + + # summary table + print() + print('=' * 70) + print('BENCH SUITE SUMMARY') + print('=' * 70) + name_w = max([len('TEST')] + [len(r[0]) for r in results]) + print('{:<{w}} {:<6} {:>8} {}'.format('TEST', 'STATUS', 'TIME(s)', 'DETAIL', w=name_w)) + print('-' * 70) + n_pass = n_fail = n_skip = 0 + for name, status, dur, detail in results: + if status == 'PASS': + n_pass += 1 + elif status == 'FAIL': + n_fail += 1 + else: + n_skip += 1 + print('{:<{w}} {:<6} {:>8.1f} {}'.format(name, status, dur, detail, w=name_w)) + print('-' * 70) + print('{} passed, {} failed, {} skipped'.format(n_pass, n_fail, n_skip)) + + sys.exit(1 if n_fail > 0 else 0) + + +if __name__ == '__main__': + main() diff --git a/Tools/bench_test/usb_replug.py b/Tools/bench_test/usb_replug.py new file mode 100755 index 00000000000..53141961a20 --- /dev/null +++ b/Tools/bench_test/usb_replug.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +""" +Guided USB replug test for a PX4 board on real NuttX hardware. + +USB re-enumeration is a stress test for the MAVLink instance lifecycle: every +time the cable is replugged the CDC ACM link tears down and comes back, and a +new MAVLink instance is (re)started for it. Before the v1.18 concurrency +rework this path shared state across the teardown; the failure we hunt is a +board that leaks a MAVLink instance per replug (instance count climbs) or +leaks RAM per replug (free used bytes climbs cycle over cycle). + +This test is operator-assisted but keyboard-free during the loop: it prints +"UNPLUG now" / "REPLUG now" and detects the device node vanishing and +returning programmatically (the node name can change across enumeration on +macOS, so we follow the returned path). After each replug it reconnects, +re-reads the MAVLink instance count and free RAM, and compares against the +baseline. + +Every wait has a timeout. A device that never comes back, or a shell command +that never completes, is reported as a FAIL naming what stalled, not a hung +script. +""" + +import argparse +import os +import re +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import px4bench + + +def count_mavlink_instances(output): + """Count MAVLink instances from `mavlink status` (instance #N blocks).""" + return len(re.findall(r'instance\s*#\s*\d+', output)) + + +def parse_free_used(output): + """Parse NuttX `free` output, return (total_bytes, used_bytes) or (None, None). + + NuttX `free` prints a header line then one or more memory-region lines: + + total used free largest ... + Umem: 262144 53016 209128 198600 ... + + The exact region label varies by build (Umem/Kmem/Mem), and column count + varies, so we parse tolerantly: find the header line (contains both + "total" and "used"), remember which column index each is, then take the + first following line that has enough integer fields and read those two + columns. If there is no recognizable header we fall back to the first data + line and assume the classic order total, used as the first two integers. + """ + lines = output.splitlines() + + for i, line in enumerate(lines): + low = line.lower() + if 'total' in low and 'used' in low: + # header found; take the first following line with numeric columns. + # A data line may carry a leading region label (e.g. "Umem:"), + # so strip a non-numeric first field and read the classic NuttX + # column order: total, used as the first two integers. + for data in lines[i + 1:]: + fields = data.split() + if len(fields) < 3: + continue + if fields and not re.match(r'^-?\d', fields[0]): + fields = fields[1:] + ints = [int(t) for t in fields if re.match(r'^\d+$', t)] + if len(ints) >= 2: + return ints[0], ints[1] + break + + # no header found: first line with >=2 integers, classic order + for line in lines: + fields = line.split() + if fields and not re.match(r'^-?\d', fields[0]): + fields = fields[1:] + ints = [int(t) for t in fields if re.match(r'^\d+$', t)] + if len(ints) >= 2: + return ints[0], ints[1] + + return None, None + + +def read_baseline(shell, report): + """Read instance count and free used bytes at baseline. Returns dict or None.""" + ms_out, timed_out = shell.run('mavlink status', timeout=10) + if timed_out: + report.fail('baseline mavlink status', + 'shell command mavlink status stalled (no completion within 10s)') + return None + instances = count_mavlink_instances(ms_out) + + free_out, timed_out = shell.run('free', timeout=10) + if timed_out: + report.fail('baseline free', + 'shell command free stalled (no completion within 10s)') + return None + total, used = parse_free_used(free_out) + if used is None: + report.fail('baseline free parse', 'could not parse used bytes from free output') + return None + + report.info('baseline: {} mavlink instance(s), free used={} bytes total={} bytes'.format( + instances, used, total)) + return {'instances': instances, 'used': used, 'total': total, + 'free_raw': free_out, 'mavlink_raw': ms_out} + + +def main(): + parser = argparse.ArgumentParser( + description='PX4 guided USB replug test: watch MAVLink instance and RAM ' + 'lifecycle across cable re-enumeration.') + px4bench.add_connection_args(parser) + parser.add_argument('--cycles', type=int, default=5, + help='number of unplug/replug cycles (default: %(default)s)') + parser.add_argument('--heartbeat-timeout', type=float, default=30, + help='seconds to wait for heartbeat after replug (default: %(default)s)') + parser.add_argument('--ram-tolerance', type=int, default=8192, + help='allowed free-used growth in bytes per cycle before FAIL ' + '(default: %(default)s)') + args = parser.parse_args() + + report = px4bench.Reporter('usb_replug') + + if not px4bench.is_serial_device(args.connection): + print('error: usb_replug requires a serial device connection ' + '(got {!r}); USB re-enumeration cannot be observed on a network link.'.format( + args.connection), file=sys.stderr) + sys.exit(2) + + device = args.connection + + # ----- baseline ----- + try: + mav = px4bench.connect(device, baud=args.baudrate, timeout=args.connect_timeout) + except (TimeoutError, OSError) as e: + report.fail('baseline connect', str(e)) + sys.exit(report.finish()) + report.ok('baseline connect', 'heartbeat from {}'.format(device)) + + shell = px4bench.MavlinkShell(mav) + if not shell.open(timeout=5): + report.fail('baseline shell', 'no nsh output on SERIAL_CONTROL within 5s') + shell.close() + mav.close() + sys.exit(report.finish()) + + baseline = read_baseline(shell, report) + shell.close() + mav.close() + if baseline is None: + sys.exit(report.finish()) + + report.ok('baseline', '{} instance(s), {} bytes used'.format( + baseline['instances'], baseline['used'])) + + last_used = baseline['used'] + + # ----- replug cycles ----- + for i in range(1, args.cycles + 1): + print('-' * 60, flush=True) + print('Cycle {}/{}: UNPLUG the USB cable now.'.format(i, args.cycles), flush=True) + + gone = px4bench.wait_device_gone(device, timeout=60) + if gone is None: + # give the operator one guided retry before failing the cycle + print('Device {} still present after 60s. Please UNPLUG it now ' + '(retrying for 30s).'.format(device), flush=True) + gone = px4bench.wait_device_gone(device, timeout=30) + if gone is None: + report.fail('cycle {} unplug'.format(i), + 'device {} never disappeared (unplug not detected within 90s)'.format( + device)) + continue + report.info('cycle {}: device gone after {:.1f}s'.format(i, gone)) + + print('Cycle {}/{}: REPLUG the USB cable now.'.format(i, args.cycles), flush=True) + newdev, back_elapsed = px4bench.wait_device_back(device, timeout=60) + if newdev is None: + report.fail('cycle {} replug'.format(i), + 'device did not reappear within 60s after unplug') + continue + if newdev != device: + report.info('cycle {}: device re-enumerated as {} (was {})'.format( + i, newdev, device)) + device = newdev # follow the possibly-renamed node + report.info('cycle {}: device back after {:.1f}s'.format(i, back_elapsed)) + + # reconnect + heartbeat within the configured budget + try: + mav = px4bench.connect(device, baud=args.baudrate, + timeout=args.heartbeat_timeout) + except (TimeoutError, OSError) as e: + report.fail('cycle {} reconnect'.format(i), + 'no heartbeat within {}s after replug: {}'.format( + args.heartbeat_timeout, e)) + continue + report.ok('cycle {} heartbeat'.format(i), + 'reconnected on {}'.format(device)) + + shell = px4bench.MavlinkShell(mav) + if not shell.open(timeout=5): + report.fail('cycle {} shell'.format(i), + 'no nsh output on SERIAL_CONTROL within 5s') + shell.close() + mav.close() + continue + + # instance count must not grow (a leak means instances pile up on replug) + ms_out, timed_out = shell.run('mavlink status', timeout=10) + if timed_out: + report.fail('cycle {}'.format(i), + 'shell command mavlink status stalled (no completion within 10s)') + shell.close() + mav.close() + continue + instances = count_mavlink_instances(ms_out) + report.check('cycle {} instances'.format(i), + instances == baseline['instances'], + 'instances={} (baseline={})'.format(instances, baseline['instances'])) + + # free used must not exceed baseline + tolerance * cycle_index (steady growth = leak) + free_out, timed_out = shell.run('free', timeout=10) + shell.close() + mav.close() + if timed_out: + report.fail('cycle {}'.format(i), + 'shell command free stalled (no completion within 10s)') + continue + _, used = parse_free_used(free_out) + if used is None: + report.fail('cycle {} free parse'.format(i), + 'could not parse used bytes from free output') + continue + budget = baseline['used'] + args.ram_tolerance * i + report.check('cycle {} ram'.format(i), used <= budget, + 'used={} bytes, budget={} bytes (baseline {} + {}*{}), ' + 'delta-since-last={:+d}'.format( + used, budget, baseline['used'], args.ram_tolerance, i, + used - last_used)) + last_used = used + + # ----- final summary ----- + print('-' * 60, flush=True) + total_growth = last_used - baseline['used'] + report.info('free used: first={} bytes, last={} bytes, net growth={:+d} bytes ' + 'over {} cycle(s)'.format( + baseline['used'], last_used, total_growth, args.cycles)) + + sys.exit(report.finish()) + + +if __name__ == '__main__': + main()