summaryrefslogtreecommitdiffstats
path: root/tools/guest-diag/qmp_record.py
blob: 026a0d84818ed03342273e7333f0371c2f3a28ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2026 Open-IOV contributors
"""
qmp_record.py - record the QEMU graphic console via QMP screendump.

The guest desktop is shown on a QEMU display device (virtio-vga); QMP
`screendump` returns the scanout as a PPM file with no guest-side capture
agent.  This script paces the dumps at a fixed rate; the host then encodes
the numbered PPM sequence with ffmpeg.

Usage:
  qmp_record.py --out DIR [--fps 12] [--duration 90] [--socket PATH]
  qmp_record.py --out DIR --until-file /tmp/stop   # stop when file exists

Every screendump is written as DIR/f000001.ppm (6-digit counter).  A
`record.log` line per second records the achieved rate and any QMP error.
Bounded: never runs without a duration or a stop file.
"""
import argparse
import json
import os
import socket
import sys
import time


def connect(path, timeout=10.0):
    s = socket.socket(socket.AF_UNIX)
    s.settimeout(timeout)
    s.connect(path)
    f = s.makefile("rwb", buffering=0)
    greet = json.loads(f.readline())
    if "QMP" not in greet:
        raise RuntimeError("not a QMP greeting: %r" % (greet,))
    f.write(json.dumps({"execute": "qmp_capabilities"}).encode() + b"\n")
    while True:
        r = json.loads(f.readline())
        if "return" in r:
            break
        if "error" in r:
            raise RuntimeError("qmp_capabilities: %r" % (r,))
    return s, f


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--socket", default="/tmp/qemu-qmp.sock")
    ap.add_argument("--out", required=True)
    ap.add_argument("--fps", type=float, default=12.0)
    ap.add_argument("--duration", type=float, default=0.0)
    ap.add_argument("--until-file", default="")
    ap.add_argument("--max-frames", type=int, default=100000)
    a = ap.parse_args()

    if a.duration <= 0 and not a.until_file:
        print("refusing to record unbounded (need --duration or --until-file)",
              file=sys.stderr)
        return 2
    os.makedirs(a.out, exist_ok=True)
    log = open(os.path.join(a.out, "record.log"), "w", buffering=1)

    sock, f = connect(a.socket)
    period = 1.0 / a.fps
    t0 = time.monotonic()
    deadline = t0 + a.duration if a.duration > 0 else 0.0
    n = 0
    nerr = 0
    next_t = t0
    last_log = t0
    while n < a.max_frames:
        now = time.monotonic()
        if deadline and now >= deadline:
            break
        if a.until_file and os.path.exists(a.until_file):
            break
        if now < next_t:
            time.sleep(next_t - now)
            now = time.monotonic()
        next_t += period
        if next_t < now:          # fell behind: resynchronise, do not burst
            next_t = now
        path = os.path.join(a.out, "f%06d.ppm" % (n + 1))
        try:
            f.write(json.dumps({"execute": "screendump",
                                "arguments": {"filename": path}}).encode() + b"\n")
            r = json.loads(f.readline())
            if "error" in r:
                nerr += 1
                log.write("ERROR %s %r\n" % (path, r["error"]))
            else:
                n += 1
        except (socket.timeout, OSError) as e:
            log.write("CONN %s %s\n" % (path, e))
            break
        if now - last_log >= 1.0:
            log.write("t=%.1f frames=%d err=%d\n" %
                      (now - t0, n, nerr))
            last_log = now
    log.write("DONE frames=%d err=%d secs=%.2f\n" %
              (n, nerr, time.monotonic() - t0))
    log.close()
    try:
        sock.close()
    except OSError:
        pass
    print("RECORDED %d frames in %.1fs (errors=%d)" % (n, time.monotonic() - t0, nerr))
    return 0 if n else 1


if __name__ == "__main__":
    sys.exit(main())