diff --git a/qemu/rootfs/etc/warden-lib.sh b/qemu/rootfs/etc/warden-lib.sh index a5d2759..4bbc5e4 100644 --- a/qemu/rootfs/etc/warden-lib.sh +++ b/qemu/rootfs/etc/warden-lib.sh @@ -69,7 +69,9 @@ warden_idle_forever() { # # `@cat PATH` is answered here and never forwarded: PATH's contents (or one # "bridge: no such file: PATH" line), which is how the json flow channel -# reads webstatus.c's snapshot from outside the VM. Everything else goes to +# reads webstatus.c's snapshot from outside the VM. `@procs` is answered +# here too: every /proc//stat line, for qmp.py's stall probe +# (flare-edge #1528). Everything else goes to # warden-ui's FIFO, and the bridge waits for the reply file the UI renames # into place whole. The previous reply is removed BEFORE sending: a fixed # settle handed back the previous command's reply (flare-edge #152). @@ -105,6 +107,11 @@ warden_ctl_bridge() { echo "bridge: no such file: $path" fi ;; + "@procs") + # Every process's stat line, for the driver's stall probe + # (qmp.py stall_report, flare-edge #1528); needs no UI. + cat /proc/[0-9]*/stat 2>/dev/null + ;; *) if [ -p "$_wcb_fifo" ]; then if [ "$_wcb_stale" = 1 ]; then diff --git a/qemu/tests/ctl-bridge-test.sh b/qemu/tests/ctl-bridge-test.sh index 8664665..9d8ff47 100755 --- a/qemu/tests/ctl-bridge-test.sh +++ b/qemu/tests/ctl-bridge-test.sh @@ -101,6 +101,16 @@ run_bridge nofifo 1 page check "missing FIFO answers at once" \ same "$WORK/nofifo.out" 'bridge: warden-ui control FIFO not present' '<>' +# @procs: the process table for the stall probe (flare-edge #1528), answered +# by the bridge itself, so it works with no UI at all. +procs_ok() { + grep -Eq '^[0-9]+ \(.*\) [A-Z] ' "$WORK/procs.out" && + [ "$(tail -n 1 "$WORK/procs.out")" = '<>' ] && + ! grep -q 'FIFO not present' "$WORK/procs.out" +} +run_bridge procs 1 @procs +check "@procs lists process stat lines without the UI" procs_ok + if [ "$FAIL" = 0 ]; then echo "ctl-bridge tests: OK ($CHECKS checks)" else diff --git a/qemu/tests/qmp.py b/qemu/tests/qmp.py index a6ff770..d7897cb 100755 --- a/qemu/tests/qmp.py +++ b/qemu/tests/qmp.py @@ -178,6 +178,11 @@ QMP_TIMEOUT_S = 20.0 # bridge's explicit "no reply" line rather than a bare socket timeout. CTL_TIMEOUT_S = 90.0 +# The bridge's own answer when warden-ui did not reply within its bound +# (Ctl.NO_REPLY; a module constant too because the offline tests swap the +# Ctl class out). +BRIDGE_NO_REPLY = "bridge: no reply from warden-ui" + # Where webstatus.c (ui-src/src/warden/webstatus.c) publishes its atomic # snapshot inside the guest. assert_json/wait_json `@cat` this path over the # control channel; see the bridge in rootfs/sbin/init. @@ -371,7 +376,7 @@ class Ctl: # The bridge's own answer when warden-ui did not reply within its bound # (warden_ctl_bridge in rootfs/etc/warden-lib.sh, flare-edge #1448). - NO_REPLY = "bridge: no reply from warden-ui" + NO_REPLY = BRIDGE_NO_REPLY def __init__(self, path, timeout=None): if timeout is None: @@ -412,6 +417,171 @@ class Ctl: return reply +# Stall probe (flare-edge #1528). When a step fails because warden-ui did not +# answer (the bridge's no-reply line) or did not consume an injected press, +# the driver samples the host, the VM's vCPU thread and the guest over +# STALL_WINDOW_S and appends one line to the step's detail, so the job log +# itself says whether the host starved the VM, the guest CPU was saturated +# (and by which processes), the guest waited on I/O, or the guest sat idle +# while warden-ui was blocked. Re-run jobs lose their artifacts; the job log +# keeps this line. At most STALL_REPORTS_MAX probes per run, since each one +# costs the window. +STALL_WINDOW_S = 2.0 +STALL_REPORTS_MAX = 3 +INPUT_NOT_CONSUMED = "was not consumed within" + + +def is_stall(detail): + """Whether a failed step's detail is warden-ui not answering.""" + return BRIDGE_NO_REPLY in detail or INPUT_NOT_CONSUMED in detail + + +def parse_proc_stat(text): + """Guest /proc/stat -> (cpu jiffies list, procs_running, procs_blocked); + None when the text has no aggregate cpu line.""" + cpu, running, blocked = None, None, None + for line in text.splitlines(): + parts = line.split() + if not parts: + continue + if parts[0] == "cpu": + cpu = [int(x) for x in parts[1:] if x.isdigit()] + elif parts[0] == "procs_running" and len(parts) > 1: + running = int(parts[1]) + elif parts[0] == "procs_blocked" and len(parts) > 1: + blocked = int(parts[1]) + if not cpu or len(cpu) < 5: + return None + return cpu, running, blocked + + +def parse_procs(text): + """/proc//stat lines (the bridge's `@procs`) -> {pid: (comm, state, + utime + stime)}. The comm may hold spaces or parentheses, so the fields + are counted from its last ')'.""" + out = {} + for line in text.splitlines(): + head, sep, tail = line.rpartition(")") + if not sep or " (" not in head: + continue + pid, _, comm = head.partition(" (") + fields = tail.split() + if not pid.strip().isdigit() or len(fields) < 13: + continue + try: + ticks = int(fields[11]) + int(fields[12]) + except ValueError: + continue + out[int(pid)] = (comm, fields[0], ticks) + return out + + +def guest_cpu_delta(a, b): + """Two parse_proc_stat() samples -> (busy share, iowait share) of the + guest CPU over the window, or None when nothing was counted.""" + if a is None or b is None: + return None + d = [y - x for x, y in zip(a[0], b[0])] + total = sum(d) + if total <= 0: + return None + idle, iowait = d[3], d[4] + return (total - idle - iowait) / total, iowait / total + + +def top_procs(a, b, total_ticks, n=3): + """The N guest processes that used the most CPU between two parse_procs() + samples, as 'comm share%' strings, and the comms in state D at the end.""" + used = [] + for pid, (comm, _state, ticks) in b.items(): + before = a.get(pid) + if before is not None and ticks > before[2]: + used.append((ticks - before[2], comm)) + used.sort(reverse=True) + top = [f"{comm} {100 * t / total_ticks:.0f}%" for t, comm in used[:n]] if total_ticks > 0 else [] + dstate = sorted({comm for comm, state, _ in b.values() if state == "D"}) + return top, dstate + + +def stall_verdict(vcpu_share, guest, blocked, dstate): + """One phrase naming the most likely cause from the probe's numbers.""" + if vcpu_share is not None and vcpu_share < 0.6: + return "the host starves the VM (its vCPU thread ran under 60% of a core)" + if guest is None: + return "the guest did not answer the probe" + busy, iowait = guest + if busy >= 0.9: + return "the guest CPU is saturated" + if iowait >= 0.3 or blocked or dstate: + return "the guest waits on I/O" + return "the guest is mostly idle: warden-ui is blocked, not starved" + + +def _read(path): + try: + with open(path) as fh: + return fh.read() + except OSError: + return "" + + +def _host_psi(kind): + m = re.search(r"some avg10=([0-9.]+)", _read(f"/proc/pressure/{kind}")) + return f"{float(m.group(1)):.0f}%" if m else "n/a" + + +def _thread_ticks(tids): + total = 0 + for tid in tids: + fields = _read(f"/proc/{tid}/stat").rpartition(")")[2].split() + if len(fields) < 13: + return None + total += int(fields[11]) + int(fields[12]) + return total + + +def _guest_sample(ctl): + try: + return parse_proc_stat(ctl.send("@cat /proc/stat")), parse_procs(ctl.send("@procs")) + except (RuntimeError, OSError): + return None, {} + + +def stall_report(ctx): + """Sample the host, the vCPU thread and the guest over STALL_WINDOW_S and + describe them in one line (see the block comment above STALL_WINDOW_S).""" + try: + tids = [c["thread-id"] for c in rpc(ctx.s, ctx.f, {"execute": "query-cpus-fast"})] + except (RuntimeError, OSError, KeyError, TypeError, ValueError): + tids = [] + hz = os.sysconf("SC_CLK_TCK") + v0 = _thread_ticks(tids) if tids else None + g0, p0 = _guest_sample(ctx.ctl) if ctx.ctl else (None, {}) + t0 = time.monotonic() + time.sleep(STALL_WINDOW_S) + v1 = _thread_ticks(tids) if tids else None + g1, p1 = _guest_sample(ctx.ctl) if ctx.ctl else (None, {}) + window = time.monotonic() - t0 + vcpu = (v1 - v0) / (hz * window) if v0 is not None and v1 is not None else None + guest = guest_cpu_delta(g0, g1) + blocked = g1[2] if g1 else None + total_ticks = sum(y - x for x, y in zip(g0[0], g1[0])) if g0 and g1 else 0 + top, dstate = top_procs(p0, p1, total_ticks) + load = os.getloadavg()[0] + parts = [f"stall probe ({window:.1f} s): {stall_verdict(vcpu, guest, blocked, dstate)}", + f"host load {load:.1f}/{os.cpu_count()} cpus, psi cpu {_host_psi('cpu')} " + f"io {_host_psi('io')}", + "vcpu " + (f"{100 * vcpu:.0f}% of a core" if vcpu is not None else "n/a")] + if guest is None: + parts.append("guest n/a") + else: + parts.append(f"guest busy {100 * guest[0]:.0f}% iowait {100 * guest[1]:.0f}%, " + f"running {g1[1]} blocked {g1[2]}") + parts.append("top " + (", ".join(top) if top else "n/a")) + parts.append("D " + (", ".join(dstate) if dstate else "none")) + return "; ".join(parts) + + HIT_RE = re.compile(r'^hit \d+,\d+: (\S+)(?: text="(.*)" box=(-?\d+),(-?\d+),(\d+)x(\d+))?$') @@ -775,6 +945,8 @@ class Ctx: self.prev_step_console = 0 # The longest input-count wait of the current tap, swipe or fling. self.input_wait_s = 0.0 + # Stall probes run so far (STALL_REPORTS_MAX bounds them). + self.stall_reports = 0 def need_ctl(self, lineno, cmd): if self.ctl is None: @@ -1289,6 +1461,14 @@ def drive(s, f, script_path, outdir, size, ctl_path=None, console_path=None, ref # Recorded the same as any other fatal row: the run keeps going # past it. result = ("fatal", str(e)) + if (result is not None and result[0] != "ok" and len(result) > 1 + and is_stall(str(result[1])) and ctx.stall_reports < STALL_REPORTS_MAX): + ctx.stall_reports += 1 + try: + probe = stall_report(ctx) + except (RuntimeError, OSError, ValueError) as e: + probe = f"stall probe failed: {e}" + result = (result[0], f"{result[1]}; {probe}") if result is not None: record(lineno, line, *result) diff --git a/qemu/tests/test_qmp_drive.py b/qemu/tests/test_qmp_drive.py index b59b051..1dea034 100755 --- a/qemu/tests/test_qmp_drive.py +++ b/qemu/tests/test_qmp_drive.py @@ -1361,5 +1361,109 @@ class JsonStatusFetch(unittest.TestCase): self.assertGreaterEqual(time.monotonic() - t0, 0.6) + +def _proc_stat(user, idle, iowait=0, running=1, blocked=0): + return (f"cpu {user} 0 0 {idle} {iowait} 0 0 0 0 0\ncpu0 {user} 0 0 {idle} {iowait} 0 0 0 0 0\n" + f"ctxt 1\nprocs_running {running}\nprocs_blocked {blocked}\n") + + +def _pid_line(pid, comm, state, utime, stime=0): + rest = " ".join(["0"] * 10) + return f"{pid} ({comm}) {state} 1 1 1 0 -1 0 0 0 0 0 {utime} {stime} {rest}" + + +class StallProbe(unittest.TestCase): + """flare-edge #1528: a step that fails because warden-ui did not answer + carries one probe line saying why (host starving the VM, guest CPU + saturated, guest I/O wait, or an idle guest with a blocked UI).""" + + def test_parsers(self): + st = qmp.parse_proc_stat(_proc_stat(5, 7, 2, running=3, blocked=1)) + self.assertEqual(st, ([5, 0, 0, 7, 2, 0, 0, 0, 0, 0], 3, 1)) + self.assertIsNone(qmp.parse_proc_stat("bridge: no such file: /proc/stat")) + procs = qmp.parse_procs(_pid_line(7, "warden ui) x", "R", 40, 2) + "\n" + + _pid_line(9, "sh", "D", 1) + "\njunk\n") + self.assertEqual(procs, {7: ("warden ui) x", "R", 42), 9: ("sh", "D", 1)}) + + def test_verdicts(self): + self.assertIn("starves the VM", qmp.stall_verdict(0.3, (1.0, 0.0), 0, [])) + self.assertIn("did not answer", qmp.stall_verdict(0.99, None, None, [])) + self.assertIn("saturated", qmp.stall_verdict(0.99, (0.95, 0.0), 0, [])) + self.assertIn("I/O", qmp.stall_verdict(0.99, (0.2, 0.5), 1, ["warden-ui"])) + self.assertIn("I/O", qmp.stall_verdict(None, (0.1, 0.0), 0, ["warden-ui"])) + self.assertIn("idle", qmp.stall_verdict(0.99, (0.05, 0.0), 0, [])) + + def test_cpu_delta_and_top(self): + a = qmp.parse_proc_stat(_proc_stat(100, 100)) + b = qmp.parse_proc_stat(_proc_stat(190, 110)) + busy, iowait = qmp.guest_cpu_delta(a, b) + self.assertAlmostEqual(busy, 0.9) + self.assertEqual(iowait, 0.0) + p0 = qmp.parse_procs(_pid_line(7, "warden-ui", "R", 10) + "\n" + _pid_line(8, "flared", "S", 5)) + p1 = qmp.parse_procs(_pid_line(7, "warden-ui", "R", 80) + "\n" + _pid_line(8, "flared", "D", 25)) + top, dstate = qmp.top_procs(p0, p1, 100) + self.assertEqual(top, ["warden-ui 70%", "flared 20%"]) + self.assertEqual(dstate, ["flared"]) + + def _drive_no_reply(self, script): + class NoReplyCtl(FakeCtl): + samples = 0 + + def send(self, cmd): + if cmd == "@cat /proc/stat": + NoReplyCtl.samples += 1 + n = NoReplyCtl.samples + return _proc_stat(100 * n, 10) + if cmd == "@procs": + n = NoReplyCtl.samples + return _pid_line(7, "warden-ui", "R", 95 * n) + "\n" + _pid_line(8, "sh", "S", 5 * n) + if cmd == "page": + raise RuntimeError("control channel: bridge: no reply from warden-ui " + "within 30 s: page") + return super().send(cmd) + + def rpc_fn(sock, sock_file, obj): + if obj.get("execute") == "query-cpus-fast": + # No vCPU thread to sample here (test_vcpu_thread_ticks + # covers the sampling); the verdict then rests on the guest. + return [] + return fake_rpc(sock, sock_file, obj) + + saved = qmp.STALL_WINDOW_S + qmp.STALL_WINDOW_S = 0.05 + try: + return run_script(script, ctl_cls=NoReplyCtl, rpc_fn=rpc_fn) + finally: + qmp.STALL_WINDOW_S = saved + + def test_no_reply_steps_carry_a_bounded_probe(self): + rc, _by, rows = self._drive_no_reply("assert_page Demo/Rows\n" * 4 + "assert_stat fps lt 0\n") + self.assertEqual(rc, 1) + self.assertEqual([r["status"] for r in rows], ["fatal"] * 4 + ["fail"]) + probed = [r["detail"] for r in rows if "stall probe" in r["detail"]] + self.assertEqual(len(probed), qmp.STALL_REPORTS_MAX, rows) + first = rows[0]["detail"] + self.assertTrue(first.startswith("control channel: bridge: no reply"), first) + self.assertIn("the guest CPU is saturated", first) + self.assertIn("top warden-ui 95%, sh 5%", first) + self.assertIn("vcpu n/a", first) + self.assertIn("guest busy 100% iowait 0%", first) + # A plain mismatch is not a stall and gets no probe. + self.assertNotIn("stall probe", rows[4]["detail"]) + + def test_vcpu_thread_ticks(self): + tid = threading.get_native_id() + before = qmp._thread_ticks([tid]) + end = time.process_time() + 0.3 + while time.process_time() < end: + pass + self.assertGreater(qmp._thread_ticks([tid]), before) + self.assertIsNone(qmp._thread_ticks([2 ** 22 + 12345])) + + def test_unconsumed_input_is_a_stall(self): + self.assertTrue(qmp.is_stall(qmp.input_verdict(SimpleNamespace(), False)[1])) + self.assertTrue(qmp.is_stall("control channel: bridge: no reply from warden-ui within 30 s: hit")) + self.assertFalse(qmp.is_stall("obj moved: box=1,2,3x4")) + if __name__ == "__main__": unittest.main(verbosity=1)