Notes about QEMU monitor.

1. Introduction

The QEMU monitor is used to give complex commands to the QEMU emulator. You can use it to:

  • Remove or insert removable media images (such as CD-ROM or floppies).
  • Freeze/unfreeze the Virtual Machine (VM) and save or restore its state from a disk file.
  • Inspect the VM state without an external debugger

1.1 commands

QEMU Monitor Commands

1
(qemu) help

2. Usage

QEMU启动时,需要使用-monitor选项指定做为console设备,官方文档说明如下:

1
2
3
4
-monitor dev
Redirect the monitor to host device dev (same devices as the serialport).
The default device is vc in graphical mode and stdio in non graphical mode.
Use -monitor none to disable the default monitor.

1
2
-serial mon:stdio
creates a multiplexed stdio backend connected to the serial port and the QEMU monitor
1
2
(qemu) info kvm
kvm support: enabled

上述这种方式更偏向用户直接输入命令进行交互,称为HMP(Human Machine Protocol),程序使用这种方式不是太方便。QEMU还提供了另外一种基于JSON的QMP(QEMU Machine Protocol)来满足自动化处理的需求。Libvirt就是使用QMP来控制QEMU实例。

3. QMP

QMP规范可以参考:

QMP协议的工作流程如下:

  • 连接建立后服务器发送欢迎信息,进入能力协商(capabilities negotiation)模式
  • 客户端发送{“execute”:”qmp_capablities”}
  • 成功则服务器返回{“return”:{}},否则return中会含有error
  • 客户端发送命令
  • 服务器以异步消息返回结果

3.1 Basic usage

1
$ qemu [...] -qmp tcp:localhost:4444,server=on,wait=off

or

1
2
3
$ qemu [...] -chardev stdio,id=mon0 -mon chardev=mon0,mode=readline \
-chardev socket,id=mon1,host=localhost,port=4444,server=on,wait=off \
-mon chardev=mon1,mode=control,pretty=on

To manually test QMP one can connect with telnet and issue commands by hand:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ telnet localhost 4444
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
{
"QMP": {
"version": {
"qemu": {
"micro": 0,
"minor": 0,
"major": 3
},
"package": "v3.0.0"
},
"capabilities": [
"oob"
]
}
}

3.2 qmp-shell

1
$ qemu [...] -qmp unix:/tmp/qmp-sock,server=on,wait=off

Run ‘qmp-shell’ (located in the source tree, under: “scripts/qmp/“) to connect to the just-launched QEMU:

1
2
3
$ ./qmp-shell -p -v /tmp/qmp-sock
[...]
(QEMU)

Virtual CPU hotplug


参考资料:

  1. QEMU Monitor
  2. QEMU monitor机制实例分析
  3. Documentation/QMP
  4. qmp-intro.txt
  5. qmp-spec.txt
  6. QEMU QMP Reference Manual