]> git.proxmox.com Git - mirror_qemu.git/blame - docs/devel/writing-qmp-commands.txt
Revert "vl: Fix to create migration object before block backends again"
[mirror_qemu.git] / docs / devel / writing-qmp-commands.txt
CommitLineData
4b389b5d
LC
1= How to write QMP commands using the QAPI framework =
2
3This document is a step-by-step guide on how to write new QMP commands using
4the QAPI framework. It also shows how to implement new style HMP commands.
5
6This document doesn't discuss QMP protocol level details, nor does it dive
7into the QAPI framework implementation.
8
9For an in-depth introduction to the QAPI framework, please refer to
b3125e73 10docs/devel/qapi-code-gen.txt. For documentation about the QMP protocol,
cfb41b88 11start with docs/interop/qmp-intro.txt.
4b389b5d
LC
12
13== Overview ==
14
15Generally speaking, the following steps should be taken in order to write a
16new QMP command.
17
bfe873e9
MA
181. Define the command and any types it needs in the appropriate QAPI
19 schema module.
4b389b5d
LC
20
212. Write the QMP command itself, which is a regular C function. Preferably,
22 the command should be exported by some QEMU subsystem. But it can also be
23 added to the qmp.c file
24
253. At this point the command can be tested under the QMP protocol
26
274. Write the HMP command equivalent. This is not required and should only be
28 done if it does make sense to have the functionality in HMP. The HMP command
29 is implemented in terms of the QMP command
30
31The following sections will demonstrate each of the steps above. We will start
32very simple and get more complex as we progress.
33
34=== Testing ===
35
36For all the examples in the next sections, the test setup is the same and is
37shown here.
38
bb46af41 39First, QEMU should be started like this:
4b389b5d 40
bb46af41 41# qemu-system-TARGET [...] \
4b389b5d
LC
42 -chardev socket,id=qmp,port=4444,host=localhost,server \
43 -mon chardev=qmp,mode=control,pretty=on
44
45Then, in a different terminal:
46
47$ telnet localhost 4444
48Trying 127.0.0.1...
49Connected to localhost.
50Escape character is '^]'.
51{
52 "QMP": {
53 "version": {
54 "qemu": {
55 "micro": 50,
56 "minor": 15,
57 "major": 0
58 },
59 "package": ""
60 },
61 "capabilities": [
62 ]
63 }
64}
65
66The above output is the QMP server saying you're connected. The server is
67actually in capabilities negotiation mode. To enter in command mode type:
68
69{ "execute": "qmp_capabilities" }
70
71Then the server should respond:
72
73{
74 "return": {
75 }
76}
77
78Which is QMP's way of saying "the latest command executed OK and didn't return
79any data". Now you're ready to enter the QMP example commands as explained in
80the following sections.
81
82== Writing a command that doesn't return data ==
83
84That's the most simple QMP command that can be written. Usually, this kind of
85command carries some meaningful action in QEMU but here it will just print
86"Hello, world" to the standard output.
87
88Our command will be called "hello-world". It takes no arguments, nor does it
89return any data.
90
bfe873e9
MA
91The first step is defining the command in the appropriate QAPI schema
92module. We pick module qapi/misc.json, and add the following line at
93the bottom:
4b389b5d
LC
94
95{ 'command': 'hello-world' }
96
97The "command" keyword defines a new QMP command. It's an JSON object. All
98schema entries are JSON objects. The line above will instruct the QAPI to
99generate any prototypes and the necessary code to marshal and unmarshal
100protocol data.
101
102The next step is to write the "hello-world" implementation. As explained
103earlier, it's preferable for commands to live in QEMU subsystems. But
104"hello-world" doesn't pertain to any, so we put its implementation in qmp.c:
105
106void qmp_hello_world(Error **errp)
107{
108 printf("Hello, world!\n");
109}
110
111There are a few things to be noticed:
112
1131. QMP command implementation functions must be prefixed with "qmp_"
1142. qmp_hello_world() returns void, this is in accordance with the fact that the
115 command doesn't return any data
1163. It takes an "Error **" argument. This is required. Later we will see how to
117 return errors and take additional arguments. The Error argument should not
118 be touched if the command doesn't return errors
1194. We won't add the function's prototype. That's automatically done by the QAPI
1205. Printing to the terminal is discouraged for QMP commands, we do it here
121 because it's the easiest way to demonstrate a QMP command
122
4b389b5d
LC
123You're done. Now build qemu, run it as suggested in the "Testing" section,
124and then type the following QMP command:
125
126{ "execute": "hello-world" }
127
128Then check the terminal running qemu and look for the "Hello, world" string. If
129you don't see it then something went wrong.
130
131=== Arguments ===
132
133Let's add an argument called "message" to our "hello-world" command. The new
134argument will contain the string to be printed to stdout. It's an optional
135argument, if it's not present we print our default "Hello, World" string.
136
137The first change we have to do is to modify the command specification in the
138schema file to the following:
139
140{ 'command': 'hello-world', 'data': { '*message': 'str' } }
141
142Notice the new 'data' member in the schema. It's an JSON object whose each
143element is an argument to the command in question. Also notice the asterisk,
144it's used to mark the argument optional (that means that you shouldn't use it
145for mandatory arguments). Finally, 'str' is the argument's type, which
146stands for "string". The QAPI also supports integers, booleans, enumerations
147and user defined types.
148
149Now, let's update our C implementation in qmp.c:
150
151void qmp_hello_world(bool has_message, const char *message, Error **errp)
152{
153 if (has_message) {
154 printf("%s\n", message);
155 } else {
156 printf("Hello, world\n");
157 }
158}
159
160There are two important details to be noticed:
161
1621. All optional arguments are accompanied by a 'has_' boolean, which is set
163 if the optional argument is present or false otherwise
1642. The C implementation signature must follow the schema's argument ordering,
165 which is defined by the "data" member
166
4b389b5d
LC
167Time to test our new version of the "hello-world" command. Build qemu, run it as
168described in the "Testing" section and then send two commands:
169
170{ "execute": "hello-world" }
171{
172 "return": {
173 }
174}
175
176{ "execute": "hello-world", "arguments": { "message": "We love qemu" } }
177{
178 "return": {
179 }
180}
181
bb46af41 182You should see "Hello, world" and "We love qemu" in the terminal running qemu,
4b389b5d
LC
183if you don't see these strings, then something went wrong.
184
185=== Errors ===
186
187QMP commands should use the error interface exported by the error.h header
455b0fde 188file. Basically, most errors are set by calling the error_setg() function.
4b389b5d
LC
189
190Let's say we don't accept the string "message" to contain the word "love". If
adb2072e 191it does contain it, we want the "hello-world" command to return an error:
4b389b5d
LC
192
193void qmp_hello_world(bool has_message, const char *message, Error **errp)
194{
195 if (has_message) {
196 if (strstr(message, "love")) {
455b0fde 197 error_setg(errp, "the word 'love' is not allowed");
4b389b5d
LC
198 return;
199 }
200 printf("%s\n", message);
201 } else {
202 printf("Hello, world\n");
203 }
204}
205
455b0fde
EB
206The first argument to the error_setg() function is the Error pointer
207to pointer, which is passed to all QMP functions. The next argument is a human
adb2072e
LC
208description of the error, this is a free-form printf-like string.
209
210Let's test the example above. Build qemu, run it as defined in the "Testing"
211section, and then issue the following command:
4b389b5d 212
adb2072e 213{ "execute": "hello-world", "arguments": { "message": "all you need is love" } }
4b389b5d
LC
214
215The QMP server's response should be:
216
217{
218 "error": {
adb2072e
LC
219 "class": "GenericError",
220 "desc": "the word 'love' is not allowed"
4b389b5d
LC
221 }
222}
223
bb46af41
MA
224Note that error_setg() produces a "GenericError" class. In general,
225all QMP errors should have that error class. There are two exceptions
226to this rule:
adb2072e 227
bb46af41
MA
228 1. To support a management application's need to recognize a specific
229 error for special handling
adb2072e 230
bb46af41 231 2. Backward compatibility
4b389b5d 232
455b0fde
EB
233If the failure you want to report falls into one of the two cases above,
234use error_set() with a second argument of an ErrorClass value.
4b389b5d 235
4b389b5d
LC
236=== Command Documentation ===
237
238There's only one step missing to make "hello-world"'s implementation complete,
239and that's its documentation in the schema file.
240
4b389b5d 241There are many examples of such documentation in the schema file already, but
bfe873e9 242here goes "hello-world"'s new entry for qapi/misc.json:
4b389b5d
LC
243
244##
245# @hello-world
246#
247# Print a client provided string to the standard output stream.
248#
1d8bda12 249# @message: string to be printed
4b389b5d
LC
250#
251# Returns: Nothing on success.
4b389b5d
LC
252#
253# Notes: if @message is not provided, the "Hello, world" string will
254# be printed instead
255#
256# Since: <next qemu stable release, eg. 1.0>
257##
258{ 'command': 'hello-world', 'data': { '*message': 'str' } }
259
260Please, note that the "Returns" clause is optional if a command doesn't return
261any data nor any errors.
262
263=== Implementing the HMP command ===
264
265Now that the QMP command is in place, we can also make it available in the human
266monitor (HMP).
267
268With the introduction of the QAPI, HMP commands make QMP calls. Most of the
269time HMP commands are simple wrappers. All HMP commands implementation exist in
270the hmp.c file.
271
272Here's the implementation of the "hello-world" HMP command:
273
274void hmp_hello_world(Monitor *mon, const QDict *qdict)
275{
276 const char *message = qdict_get_try_str(qdict, "message");
e940f543 277 Error *err = NULL;
4b389b5d 278
e940f543
MA
279 qmp_hello_world(!!message, message, &err);
280 if (err) {
281 monitor_printf(mon, "%s\n", error_get_pretty(err));
282 error_free(err);
4b389b5d
LC
283 return;
284 }
285}
286
287Also, you have to add the function's prototype to the hmp.h file.
288
289There are three important points to be noticed:
290
2911. The "mon" and "qdict" arguments are mandatory for all HMP functions. The
292 former is the monitor object. The latter is how the monitor passes
293 arguments entered by the user to the command implementation
2942. hmp_hello_world() performs error checking. In this example we just print
295 the error description to the user, but we could do more, like taking
296 different actions depending on the error qmp_hello_world() returns
e940f543 2973. The "err" variable must be initialized to NULL before performing the
4b389b5d
LC
298 QMP call
299
300There's one last step to actually make the command available to monitor users,
301we should add it to the hmp-commands.hx file:
302
303 {
304 .name = "hello-world",
305 .args_type = "message:s?",
306 .params = "hello-world [message]",
307 .help = "Print message to the standard output",
2b9e3576 308 .cmd = hmp_hello_world,
4b389b5d
LC
309 },
310
311STEXI
312@item hello_world @var{message}
313@findex hello_world
314Print message to the standard output
315ETEXI
316
317To test this you have to open a user monitor and issue the "hello-world"
318command. It might be instructive to check the command's documentation with
319HMP's "help" command.
320
321Please, check the "-monitor" command-line option to know how to open a user
322monitor.
323
324== Writing a command that returns data ==
325
326A QMP command is capable of returning any data the QAPI supports like integers,
327strings, booleans, enumerations and user defined types.
328
329In this section we will focus on user defined types. Please, check the QAPI
330documentation for information about the other types.
331
332=== User Defined Types ===
333
e218052f
MA
334FIXME This example needs to be redone after commit 6d32717
335
4b389b5d
LC
336For this example we will write the query-alarm-clock command, which returns
337information about QEMU's timer alarm. For more information about it, please
338check the "-clock" command-line option.
339
340We want to return two pieces of information. The first one is the alarm clock's
341name. The second one is when the next alarm will fire. The former information is
342returned as a string, the latter is an integer in nanoseconds (which is not
343very useful in practice, as the timer has probably already fired when the
344information reaches the client).
345
346The best way to return that data is to create a new QAPI type, as shown below:
347
348##
349# @QemuAlarmClock
350#
351# QEMU alarm clock information.
352#
353# @clock-name: The alarm clock method's name.
354#
1d8bda12 355# @next-deadline: The time (in nanoseconds) the next alarm will fire.
4b389b5d
LC
356#
357# Since: 1.0
358##
359{ 'type': 'QemuAlarmClock',
360 'data': { 'clock-name': 'str', '*next-deadline': 'int' } }
361
362The "type" keyword defines a new QAPI type. Its "data" member contains the
363type's members. In this example our members are the "clock-name" and the
364"next-deadline" one, which is optional.
365
366Now let's define the query-alarm-clock command:
367
368##
369# @query-alarm-clock
370#
371# Return information about QEMU's alarm clock.
372#
373# Returns a @QemuAlarmClock instance describing the alarm clock method
374# being currently used by QEMU (this is usually set by the '-clock'
375# command-line option).
376#
377# Since: 1.0
378##
379{ 'command': 'query-alarm-clock', 'returns': 'QemuAlarmClock' }
380
381Notice the "returns" keyword. As its name suggests, it's used to define the
382data returned by a command.
383
384It's time to implement the qmp_query_alarm_clock() function, you can put it
385in the qemu-timer.c file:
386
387QemuAlarmClock *qmp_query_alarm_clock(Error **errp)
388{
389 QemuAlarmClock *clock;
390 int64_t deadline;
391
392 clock = g_malloc0(sizeof(*clock));
393
394 deadline = qemu_next_alarm_deadline();
395 if (deadline > 0) {
396 clock->has_next_deadline = true;
397 clock->next_deadline = deadline;
398 }
399 clock->clock_name = g_strdup(alarm_timer->name);
400
401 return clock;
402}
403
404There are a number of things to be noticed:
405
4061. The QemuAlarmClock type is automatically generated by the QAPI framework,
407 its members correspond to the type's specification in the schema file
4082. As specified in the schema file, the function returns a QemuAlarmClock
409 instance and takes no arguments (besides the "errp" one, which is mandatory
410 for all QMP functions)
4113. The "clock" variable (which will point to our QAPI type instance) is
412 allocated by the regular g_malloc0() function. Note that we chose to
dabdf394 413 initialize the memory to zero. This is recommended for all QAPI types, as
4b389b5d
LC
414 it helps avoiding bad surprises (specially with booleans)
4154. Remember that "next_deadline" is optional? All optional members have a
416 'has_TYPE_NAME' member that should be properly set by the implementation,
417 as shown above
4185. Even static strings, such as "alarm_timer->name", should be dynamically
419 allocated by the implementation. This is so because the QAPI also generates
420 a function to free its types and it cannot distinguish between dynamically
421 or statically allocated strings
eb815e24 4226. You have to include "qapi/qapi-commands-misc.h" in qemu-timer.c
4b389b5d 423
4b389b5d
LC
424Time to test the new command. Build qemu, run it as described in the "Testing"
425section and try this:
426
427{ "execute": "query-alarm-clock" }
428{
429 "return": {
430 "next-deadline": 2368219,
431 "clock-name": "dynticks"
432 }
433}
434
435==== The HMP command ====
436
437Here's the HMP counterpart of the query-alarm-clock command:
438
439void hmp_info_alarm_clock(Monitor *mon)
440{
441 QemuAlarmClock *clock;
e940f543 442 Error *err = NULL;
4b389b5d 443
e940f543
MA
444 clock = qmp_query_alarm_clock(&err);
445 if (err) {
4b389b5d 446 monitor_printf(mon, "Could not query alarm clock information\n");
e940f543 447 error_free(err);
4b389b5d
LC
448 return;
449 }
450
451 monitor_printf(mon, "Alarm clock method in use: '%s'\n", clock->clock_name);
452 if (clock->has_next_deadline) {
453 monitor_printf(mon, "Next alarm will fire in %" PRId64 " nanoseconds\n",
454 clock->next_deadline);
455 }
456
457 qapi_free_QemuAlarmClock(clock);
458}
459
460It's important to notice that hmp_info_alarm_clock() calls
461qapi_free_QemuAlarmClock() to free the data returned by qmp_query_alarm_clock().
462For user defined types, the QAPI will generate a qapi_free_QAPI_TYPE_NAME()
463function and that's what you have to use to free the types you define and
464qapi_free_QAPI_TYPE_NAMEList() for list types (explained in the next section).
465If the QMP call returns a string, then you should g_free() to free it.
466
467Also note that hmp_info_alarm_clock() performs error handling. That's not
468strictly required if you're sure the QMP function doesn't return errors, but
469it's good practice to always check for errors.
470
471Another important detail is that HMP's "info" commands don't go into the
472hmp-commands.hx. Instead, they go into the info_cmds[] table, which is defined
473in the monitor.c file. The entry for the "info alarmclock" follows:
474
475 {
476 .name = "alarmclock",
477 .args_type = "",
478 .params = "",
479 .help = "show information about the alarm clock",
2b9e3576 480 .cmd = hmp_info_alarm_clock,
4b389b5d
LC
481 },
482
483To test this, run qemu and type "info alarmclock" in the user monitor.
484
485=== Returning Lists ===
486
487For this example, we're going to return all available methods for the timer
488alarm, which is pretty much what the command-line option "-clock ?" does,
489except that we're also going to inform which method is in use.
490
491This first step is to define a new type:
492
493##
494# @TimerAlarmMethod
495#
496# Timer alarm method information.
497#
498# @method-name: The method's name.
499#
500# @current: true if this alarm method is currently in use, false otherwise
501#
502# Since: 1.0
503##
504{ 'type': 'TimerAlarmMethod',
505 'data': { 'method-name': 'str', 'current': 'bool' } }
506
507The command will be called "query-alarm-methods", here is its schema
508specification:
509
510##
511# @query-alarm-methods
512#
513# Returns information about available alarm methods.
514#
515# Returns: a list of @TimerAlarmMethod for each method
516#
517# Since: 1.0
518##
519{ 'command': 'query-alarm-methods', 'returns': ['TimerAlarmMethod'] }
520
521Notice the syntax for returning lists "'returns': ['TimerAlarmMethod']", this
522should be read as "returns a list of TimerAlarmMethod instances".
523
524The C implementation follows:
525
526TimerAlarmMethodList *qmp_query_alarm_methods(Error **errp)
527{
528 TimerAlarmMethodList *method_list = NULL;
529 const struct qemu_alarm_timer *p;
530 bool current = true;
531
532 for (p = alarm_timers; p->name; p++) {
533 TimerAlarmMethodList *info = g_malloc0(sizeof(*info));
534 info->value = g_malloc0(sizeof(*info->value));
535 info->value->method_name = g_strdup(p->name);
536 info->value->current = current;
537
538 current = false;
539
540 info->next = method_list;
541 method_list = info;
542 }
543
544 return method_list;
545}
546
547The most important difference from the previous examples is the
548TimerAlarmMethodList type, which is automatically generated by the QAPI from
549the TimerAlarmMethod type.
550
551Each list node is represented by a TimerAlarmMethodList instance. We have to
552allocate it, and that's done inside the for loop: the "info" pointer points to
553an allocated node. We also have to allocate the node's contents, which is
554stored in its "value" member. In our example, the "value" member is a pointer
555to an TimerAlarmMethod instance.
556
557Notice that the "current" variable is used as "true" only in the first
5708b2b7 558iteration of the loop. That's because the alarm timer method in use is the
4b389b5d
LC
559first element of the alarm_timers array. Also notice that QAPI lists are handled
560by hand and we return the head of the list.
561
4b389b5d
LC
562Now Build qemu, run it as explained in the "Testing" section and try our new
563command:
564
565{ "execute": "query-alarm-methods" }
566{
567 "return": [
568 {
569 "current": false,
570 "method-name": "unix"
571 },
572 {
573 "current": true,
574 "method-name": "dynticks"
575 }
576 ]
577}
578
579The HMP counterpart is a bit more complex than previous examples because it
580has to traverse the list, it's shown below for reference:
581
582void hmp_info_alarm_methods(Monitor *mon)
583{
584 TimerAlarmMethodList *method_list, *method;
e940f543 585 Error *err = NULL;
4b389b5d 586
e940f543
MA
587 method_list = qmp_query_alarm_methods(&err);
588 if (err) {
4b389b5d 589 monitor_printf(mon, "Could not query alarm methods\n");
e940f543 590 error_free(err);
4b389b5d
LC
591 return;
592 }
593
594 for (method = method_list; method; method = method->next) {
595 monitor_printf(mon, "%c %s\n", method->value->current ? '*' : ' ',
596 method->value->method_name);
597 }
598
599 qapi_free_TimerAlarmMethodList(method_list);
600}