Skip to main content

windows_headless/
qmp.rs

1use anyhow::{Context, Result};
2use serde_json::{Value as Json, json};
3use std::sync::atomic::{AtomicU64, Ordering};
4use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
5use tokio::sync::mpsc;
6
7/// Hand-rolled QMP client: transport-agnostic socket + newline-delimited
8/// JSON. No `qapi` dependency; `id`-based demux of responses vs async
9/// `event`s. One client = one session: single-client transports
10/// (Windows named pipes) refuse overlap, so callers connect, act, and
11/// drop — never hold two clients to the same endpoint.
12pub struct QmpClient {
13    writer: tokio::io::WriteHalf<crate::ipc::Stream>,
14    reader: BufReader<tokio::io::ReadHalf<crate::ipc::Stream>>,
15    next_id: AtomicU64,
16    pub events: mpsc::UnboundedReceiver<Json>,
17    event_tx: mpsc::UnboundedSender<Json>,
18}
19
20impl QmpClient {
21    pub async fn connect(path: &str) -> Result<Self> {
22        let stream = crate::ipc::connect(path).await?;
23        let (rh, wh) = tokio::io::split(stream);
24        let (tx, rx) = mpsc::unbounded_channel();
25        let mut c = Self {
26            writer: wh,
27            reader: BufReader::new(rh),
28            next_id: AtomicU64::new(1),
29            events: rx,
30            event_tx: tx,
31        };
32        // Greeting: {"QMP": {"version": ...}}
33        let mut line = String::new();
34        c.reader
35            .read_line(&mut line)
36            .await
37            .context("QMP greeting")?;
38        let v: Json = serde_json::from_str(&line).context("parse QMP greeting")?;
39        if v.get("QMP").is_none() {
40            anyhow::bail!("unexpected QMP greeting: {line}");
41        }
42        // Enter command mode.
43        let res = c
44            .execute_raw(json!({"execute": "qmp_capabilities"}))
45            .await?;
46        if res.get("error").is_some() {
47            anyhow::bail!("qmp_capabilities failed: {res}");
48        }
49        Ok(c)
50    }
51
52    async fn execute_raw(&mut self, mut payload: Json) -> Result<Json> {
53        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
54        payload["id"] = json!(id);
55        let mut msg = serde_json::to_vec(&payload)?;
56        msg.push(b'\n');
57        self.writer.write_all(&msg).await.context("QMP write")?;
58        loop {
59            let mut line = String::new();
60            let n = self.reader.read_line(&mut line).await.context("QMP read")?;
61            if n == 0 {
62                anyhow::bail!("QMP socket closed");
63            }
64            let v: Json =
65                serde_json::from_str(&line).with_context(|| format!("parse QMP frame: {line}"))?;
66            if v.get("event").is_some() {
67                let _ = self.event_tx.send(v);
68                continue;
69            }
70            if v.get("id").and_then(|i| i.as_u64()) == Some(id) {
71                return Ok(v);
72            }
73            // Untagged return (older QEMU): accept if it carries return/error.
74            if v.get("return").is_some() || v.get("error").is_some() {
75                return Ok(v);
76            }
77        }
78    }
79
80    pub async fn execute(&mut self, payload: Json) -> Result<Json> {
81        let res = self.execute_raw(payload).await?;
82        if let Some(err) = res.get("error") {
83            anyhow::bail!("QMP error: {err}");
84        }
85        Ok(res)
86    }
87
88    /// Zero-downtime pivot to a new overlay (modern `node-name` form).
89    pub async fn live_overlay(&mut self, node: &str, overlay_path: &str) -> Result<()> {
90        let res = self
91            .execute(json!({
92                "execute": "blockdev-snapshot-sync",
93                "arguments": {
94                    "node-name": node,
95                    "snapshot-file": overlay_path,
96                    "snapshot-node-name": format!("{node}-overlay"),
97                    "format": "qcow2"
98                }
99            }))
100            .await;
101        if let Err(e) = res {
102            // Fallback for old QEMU which wants `device` instead of `node-name`.
103            let msg = format!("{e:#}");
104            if msg.contains("node-name") || msg.contains("invalid") || msg.contains("not found") {
105                self.execute(json!({
106                    "execute": "blockdev-snapshot-sync",
107                    "arguments": {
108                        "device": node,
109                        "snapshot-file": overlay_path,
110                        "format": "qcow2"
111                    }
112                }))
113                .await?;
114                return Ok(());
115            }
116            return Err(e);
117        }
118        Ok(())
119    }
120
121    /// HMP escape hatch for full state checkpoints. Returns the HMP output
122    /// text: success prints nothing, so ANY output is suspect (a refusal
123    /// like the pflash veto surfaces here rather than as a QMP error —
124    /// observed live as a silent no-op save). Callers check the text.
125    pub async fn savevm(&mut self, name: &str) -> Result<String> {
126        let res = self
127            .execute(json!({
128                "execute": "human-monitor-command",
129                "arguments": { "command-line": format!("savevm {name}") }
130            }))
131            .await?;
132        Ok(res
133            .get("return")
134            .and_then(|v| v.as_str())
135            .unwrap_or_default()
136            .to_string())
137    }
138
139    /// Live RAM + device migration to a file (`snapshot --live`): unlike
140    /// `savevm`, migration transfers pflash content instead of refusing
141    /// it, so the writable-VARS veto does not apply. Async job — poll
142    /// [`QmpClient::query_migrate_status`] until `completed`.
143    pub async fn migrate_to_file(&mut self, file: &std::path::Path) -> Result<()> {
144        self.execute(json!({
145            "execute": "migrate",
146            "arguments": { "uri": crate::commands::migrate_write_uri(file) }
147        }))
148        .await?;
149        Ok(())
150    }
151
152    /// Migration job status (`active`, `completed`, `failed`, `cancelled`,
153    /// ...). Bails on unexpected shapes — a status we cannot parse is not
154    /// a status we should wait on.
155    pub async fn query_migrate_status(&mut self) -> Result<String> {
156        let res = self.execute(json!({ "execute": "query-migrate" })).await?;
157        res.get("return")
158            .and_then(|r| r.get("status"))
159            .and_then(|s| s.as_str())
160            .map(str::to_string)
161            .ok_or_else(|| anyhow::anyhow!("unparseable query-migrate: {res}"))
162    }
163
164    /// VM run state (`running`, `paused`, ...). After a migration the guest
165    /// must be `running` — a completed job can still leave it paused, which
166    /// reads as a lockup from the outside.
167    pub async fn query_vm_status(&mut self) -> Result<String> {
168        let res = self.execute(json!({ "execute": "query-status" })).await?;
169        res.get("return")
170            .and_then(|r| r.get("status"))
171            .and_then(|s| s.as_str())
172            .map(str::to_string)
173            .ok_or_else(|| anyhow::anyhow!("unparseable query-status: {res}"))
174    }
175
176    /// Resume a paused VM. No-op against a running one is an error from
177    /// QEMU, so callers check [`QmpClient::query_vm_status`] first.
178    pub async fn resume_vm(&mut self) -> Result<()> {
179        self.execute(json!({ "execute": "cont" })).await?;
180        Ok(())
181    }
182
183    /// Pause a running VM. Used post-restore as half of a stop/cont cycle:
184    /// HVF can fail to re-arm halted-vCPU timers on the incoming path, and
185    /// a pause/resume round-trip re-arms them (observed downstream fix).
186    pub async fn pause_vm(&mut self) -> Result<()> {
187        self.execute(json!({ "execute": "stop" })).await?;
188        Ok(())
189    }
190
191    /// HMP escape hatch for state restore. Same output-text contract as
192    /// [`QmpClient::savevm`]: empty is success, anything else is a refusal.
193    /// (Kept for forensics; the live path resumes via `-incoming`, not this.)
194    pub async fn loadvm(&mut self, name: &str) -> Result<String> {
195        let res = self
196            .execute(json!({
197                "execute": "human-monitor-command",
198                "arguments": { "command-line": format!("loadvm {name}") }
199            }))
200            .await?;
201        Ok(res
202            .get("return")
203            .and_then(|v| v.as_str())
204            .unwrap_or_default()
205            .to_string())
206    }
207
208    /// ACPI power-button event: the guest OS shuts itself down cleanly
209    /// (no NTFS dirty bit), then QEMU exits on its own. Prefer over `quit`
210    /// for Windows guests; `quit` is the last resort.
211    pub async fn powerdown(&mut self) -> Result<()> {
212        self.execute(json!({"execute": "system_powerdown"})).await?;
213        Ok(())
214    }
215
216    /// Graceful shutdown: QEMU exits, usually without sending a response,
217    /// so drain until EOF instead of waiting for a matching `id`.
218    pub async fn quit(&mut self) -> Result<()> {
219        use tokio::io::AsyncReadExt;
220        let mut msg = serde_json::to_vec(&json!({"execute": "quit"}))?;
221        msg.push(b'\n');
222        self.writer
223            .write_all(&msg)
224            .await
225            .context("QMP quit write")?;
226        let mut rest = String::new();
227        let _ = self.reader.read_to_string(&mut rest).await;
228        Ok(())
229    }
230
231    /// Screenshot of the virtual framebuffer (preferred over monitor `nc -U`).
232    pub async fn screendump(&mut self, filename: &str) -> Result<()> {
233        self.execute(json!({
234            "execute": "human-monitor-command",
235            "arguments": { "command-line": format!("screendump {filename}") }
236        }))
237        .await?;
238        Ok(())
239    }
240
241    /// Tap guest keys (QMP `send-key`), e.g. `["ret"]` to answer the
242    /// Windows ISO's "press any key to boot from CD" prompt.
243    pub async fn send_keys(&mut self, keys: &[&str]) -> Result<()> {
244        self.execute(send_keys_payload(keys)).await?;
245        Ok(())
246    }
247
248    /// Build (but do not send) a response-check helper for unit tests.
249    pub fn check_no_error(res: &Json) -> Result<()> {
250        if let Some(err) = res.get("error") {
251            anyhow::bail!("QMP error: {err}");
252        }
253        Ok(())
254    }
255}
256
257/// Pure payload builders (unit-testable without a live VM).
258pub fn blockdev_snapshot_payload(node: &str, overlay: &str) -> Json {
259    json!({
260        "execute": "blockdev-snapshot-sync",
261        "arguments": {
262            "node-name": node,
263            "snapshot-file": overlay,
264            "snapshot-node-name": format!("{node}-overlay"),
265            "format": "qcow2"
266        }
267    })
268}
269
270pub fn hmp_payload(command_line: &str) -> Json {
271    json!({
272        "execute": "human-monitor-command",
273        "arguments": { "command-line": command_line }
274    })
275}
276
277pub fn send_keys_payload(keys: &[&str]) -> Json {
278    // QMP KeyValue union form: {"type": "qcode", "data": "<QKeyCode>"}.
279    // ("ret" = Return.) The {"key": ...} shape is rejected with
280    // "Invalid parameter type" — a silent failure we hit in testing.
281    json!({
282        "execute": "send-key",
283        "arguments": {
284            "keys": keys.iter().map(|k| json!({"type": "qcode", "data": k})).collect::<Vec<_>>()
285        }
286    })
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    #[test]
294    fn payload_shapes() {
295        let p = blockdev_snapshot_payload("drive0", "/tmp/o.qcow2");
296        assert_eq!(p["execute"], "blockdev-snapshot-sync");
297        assert_eq!(p["arguments"]["node-name"], "drive0");
298        let h = hmp_payload("savevm ckpt");
299        assert_eq!(h["arguments"]["command-line"], "savevm ckpt");
300        let k = send_keys_payload(&["ret"]);
301        assert_eq!(k["execute"], "send-key");
302        assert_eq!(k["arguments"]["keys"][0]["type"], "qcode");
303        assert_eq!(k["arguments"]["keys"][0]["data"], "ret");
304    }
305
306    #[test]
307    fn error_detection() {
308        assert!(QmpClient::check_no_error(&json!({"return": {}})).is_ok());
309        assert!(QmpClient::check_no_error(&json!({"error": {"desc": "x"}})).is_err());
310    }
311
312    #[test]
313    fn demux_id_vs_event() {
314        // Logic-level: frames with "event" go to the channel, matching "id" wins.
315        let frames = vec![
316            json!({"event": "DEVICE_DELETED"}),
317            json!({"return": {}, "id": 7}),
318        ];
319        let mut got_event = false;
320        for f in frames {
321            if f.get("event").is_some() {
322                got_event = true;
323                continue;
324            }
325            assert_eq!(f["id"], 7);
326        }
327        assert!(got_event);
328    }
329}