]> git.proxmox.com Git - mirror_qemu.git/blame - docs/writing-qmp-commands.txt
valgrind/i386: avoid false positives on KVM_SET_CLOCK ioctl
[mirror_qemu.git] / docs / 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
10docs/qapi-code-gen.txt. For documentation about the QMP protocol, please
11check the files in QMP/.
12
13== Overview ==
14
15Generally speaking, the following steps should be taken in order to write a
16new QMP command.
17
181. Write the command's and type(s) specification in the QAPI schema file
19 (qapi-schema.json in the root source directory)
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
39First, QEMU should be started as:
40
41# /path/to/your/source/qemu [...] \
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
91The first step is to add the following line to the bottom of the
92qapi-schema.json file:
93
94{ 'command': 'hello-world' }
95
96The "command" keyword defines a new QMP command. It's an JSON object. All
97schema entries are JSON objects. The line above will instruct the QAPI to
98generate any prototypes and the necessary code to marshal and unmarshal
99protocol data.
100
101The next step is to write the "hello-world" implementation. As explained
102earlier, it's preferable for commands to live in QEMU subsystems. But
103"hello-world" doesn't pertain to any, so we put its implementation in qmp.c:
104
105void qmp_hello_world(Error **errp)
106{
107 printf("Hello, world!\n");
108}
109
110There are a few things to be noticed:
111
1121. QMP command implementation functions must be prefixed with "qmp_"
1132. qmp_hello_world() returns void, this is in accordance with the fact that the
114 command doesn't return any data
1153. It takes an "Error **" argument. This is required. Later we will see how to
116 return errors and take additional arguments. The Error argument should not
117 be touched if the command doesn't return errors
1184. We won't add the function's prototype. That's automatically done by the QAPI
1195. Printing to the terminal is discouraged for QMP commands, we do it here
120 because it's the easiest way to demonstrate a QMP command
121
122Now a little hack is needed. As we're still using the old QMP server we need
123to add the new command to its internal dispatch table. This step won't be
124required in the near future. Open the qmp-commands.hx file and add the
125following in the botton:
126
127 {
128 .name = "hello-world",
129 .args_type = "",
130 .mhandler.cmd_new = qmp_marshal_input_hello_world,
131 },
132
133You're done. Now build qemu, run it as suggested in the "Testing" section,
134and then type the following QMP command:
135
136{ "execute": "hello-world" }
137
138Then check the terminal running qemu and look for the "Hello, world" string. If
139you don't see it then something went wrong.
140
141=== Arguments ===
142
143Let's add an argument called "message" to our "hello-world" command. The new
144argument will contain the string to be printed to stdout. It's an optional
145argument, if it's not present we print our default "Hello, World" string.
146
147The first change we have to do is to modify the command specification in the
148schema file to the following:
149
150{ 'command': 'hello-world', 'data': { '*message': 'str' } }
151
152Notice the new 'data' member in the schema. It's an JSON object whose each
153element is an argument to the command in question. Also notice the asterisk,
154it's used to mark the argument optional (that means that you shouldn't use it
155for mandatory arguments). Finally, 'str' is the argument's type, which
156stands for "string". The QAPI also supports integers, booleans, enumerations
157and user defined types.
158
159Now, let's update our C implementation in qmp.c:
160
161void qmp_hello_world(bool has_message, const char *message, Error **errp)
162{
163 if (has_message) {
164 printf("%s\n", message);
165 } else {
166 printf("Hello, world\n");
167 }
168}
169
170There are two important details to be noticed:
171
1721. All optional arguments are accompanied by a 'has_' boolean, which is set
173 if the optional argument is present or false otherwise
1742. The C implementation signature must follow the schema's argument ordering,
175 which is defined by the "data" member
176
177The last step is to update the qmp-commands.hx file:
178
179 {
180 .name = "hello-world",
181 .args_type = "message:s?",
182 .mhandler.cmd_new = qmp_marshal_input_hello_world,
183 },
184
185Notice that the "args_type" member got our "message" argument. The character
186"s" stands for "string" and "?" means it's optional. This too must be ordered
187according to the C implementation and schema file. You can look for more
188examples in the qmp-commands.hx file if you need to define more arguments.
189
190Again, this step won't be required in the future.
191
192Time to test our new version of the "hello-world" command. Build qemu, run it as
193described in the "Testing" section and then send two commands:
194
195{ "execute": "hello-world" }
196{
197 "return": {
198 }
199}
200
201{ "execute": "hello-world", "arguments": { "message": "We love qemu" } }
202{
203 "return": {
204 }
205}
206
207You should see "Hello, world" and "we love qemu" in the terminal running qemu,
208if you don't see these strings, then something went wrong.
209
210=== Errors ===
211
212QMP commands should use the error interface exported by the error.h header
adb2072e 213file. Basically, errors are set by calling the error_set() function.
4b389b5d
LC
214
215Let's say we don't accept the string "message" to contain the word "love". If
adb2072e 216it does contain it, we want the "hello-world" command to return an error:
4b389b5d
LC
217
218void qmp_hello_world(bool has_message, const char *message, Error **errp)
219{
220 if (has_message) {
221 if (strstr(message, "love")) {
adb2072e
LC
222 error_set(errp, ERROR_CLASS_GENERIC_ERROR,
223 "the word 'love' is not allowed");
4b389b5d
LC
224 return;
225 }
226 printf("%s\n", message);
227 } else {
228 printf("Hello, world\n");
229 }
230}
231
adb2072e
LC
232The first argument to the error_set() function is the Error pointer to pointer,
233which is passed to all QMP functions. The second argument is a ErrorClass
234value, which should be ERROR_CLASS_GENERIC_ERROR most of the time (more
235details about error classes are given below). The third argument is a human
236description of the error, this is a free-form printf-like string.
237
238Let's test the example above. Build qemu, run it as defined in the "Testing"
239section, and then issue the following command:
4b389b5d 240
adb2072e 241{ "execute": "hello-world", "arguments": { "message": "all you need is love" } }
4b389b5d
LC
242
243The QMP server's response should be:
244
245{
246 "error": {
adb2072e
LC
247 "class": "GenericError",
248 "desc": "the word 'love' is not allowed"
4b389b5d
LC
249 }
250}
251
adb2072e
LC
252As a general rule, all QMP errors should use ERROR_CLASS_GENERIC_ERROR. There
253are two exceptions to this rule:
254
255 1. A non-generic ErrorClass value exists* for the failure you want to report
256 (eg. DeviceNotFound)
257
258 2. Management applications have to take special action on the failure you
259 want to report, hence you have to add a new ErrorClass value so that they
260 can check for it
4b389b5d 261
adb2072e
LC
262If the failure you want to report doesn't fall in one of the two cases above,
263just report ERROR_CLASS_GENERIC_ERROR.
4b389b5d 264
adb2072e 265 * All existing ErrorClass values are defined in the qapi-schema.json file
4b389b5d
LC
266
267=== Command Documentation ===
268
269There's only one step missing to make "hello-world"'s implementation complete,
270and that's its documentation in the schema file.
271
272This is very important. No QMP command will be accepted in QEMU without proper
273documentation.
274
275There are many examples of such documentation in the schema file already, but
276here goes "hello-world"'s new entry for the qapi-schema.json file:
277
278##
279# @hello-world
280#
281# Print a client provided string to the standard output stream.
282#
283# @message: #optional string to be printed
284#
285# Returns: Nothing on success.
4b389b5d
LC
286#
287# Notes: if @message is not provided, the "Hello, world" string will
288# be printed instead
289#
290# Since: <next qemu stable release, eg. 1.0>
291##
292{ 'command': 'hello-world', 'data': { '*message': 'str' } }
293
294Please, note that the "Returns" clause is optional if a command doesn't return
295any data nor any errors.
296
297=== Implementing the HMP command ===
298
299Now that the QMP command is in place, we can also make it available in the human
300monitor (HMP).
301
302With the introduction of the QAPI, HMP commands make QMP calls. Most of the
303time HMP commands are simple wrappers. All HMP commands implementation exist in
304the hmp.c file.
305
306Here's the implementation of the "hello-world" HMP command:
307
308void hmp_hello_world(Monitor *mon, const QDict *qdict)
309{
310 const char *message = qdict_get_try_str(qdict, "message");
e940f543 311 Error *err = NULL;
4b389b5d 312
e940f543
MA
313 qmp_hello_world(!!message, message, &err);
314 if (err) {
315 monitor_printf(mon, "%s\n", error_get_pretty(err));
316 error_free(err);
4b389b5d
LC
317 return;
318 }
319}
320
321Also, you have to add the function's prototype to the hmp.h file.
322
323There are three important points to be noticed:
324
3251. The "mon" and "qdict" arguments are mandatory for all HMP functions. The
326 former is the monitor object. The latter is how the monitor passes
327 arguments entered by the user to the command implementation
3282. hmp_hello_world() performs error checking. In this example we just print
329 the error description to the user, but we could do more, like taking
330 different actions depending on the error qmp_hello_world() returns
e940f543 3313. The "err" variable must be initialized to NULL before performing the
4b389b5d
LC
332 QMP call
333
334There's one last step to actually make the command available to monitor users,
335we should add it to the hmp-commands.hx file:
336
337 {
338 .name = "hello-world",
339 .args_type = "message:s?",
340 .params = "hello-world [message]",
341 .help = "Print message to the standard output",
342 .mhandler.cmd = hmp_hello_world,
343 },
344
345STEXI
346@item hello_world @var{message}
347@findex hello_world
348Print message to the standard output
349ETEXI
350
351To test this you have to open a user monitor and issue the "hello-world"
352command. It might be instructive to check the command's documentation with
353HMP's "help" command.
354
355Please, check the "-monitor" command-line option to know how to open a user
356monitor.
357
358== Writing a command that returns data ==
359
360A QMP command is capable of returning any data the QAPI supports like integers,
361strings, booleans, enumerations and user defined types.
362
363In this section we will focus on user defined types. Please, check the QAPI
364documentation for information about the other types.
365
366=== User Defined Types ===
367
e218052f
MA
368FIXME This example needs to be redone after commit 6d32717
369
4b389b5d
LC
370For this example we will write the query-alarm-clock command, which returns
371information about QEMU's timer alarm. For more information about it, please
372check the "-clock" command-line option.
373
374We want to return two pieces of information. The first one is the alarm clock's
375name. The second one is when the next alarm will fire. The former information is
376returned as a string, the latter is an integer in nanoseconds (which is not
377very useful in practice, as the timer has probably already fired when the
378information reaches the client).
379
380The best way to return that data is to create a new QAPI type, as shown below:
381
382##
383# @QemuAlarmClock
384#
385# QEMU alarm clock information.
386#
387# @clock-name: The alarm clock method's name.
388#
389# @next-deadline: #optional The time (in nanoseconds) the next alarm will fire.
390#
391# Since: 1.0
392##
393{ 'type': 'QemuAlarmClock',
394 'data': { 'clock-name': 'str', '*next-deadline': 'int' } }
395
396The "type" keyword defines a new QAPI type. Its "data" member contains the
397type's members. In this example our members are the "clock-name" and the
398"next-deadline" one, which is optional.
399
400Now let's define the query-alarm-clock command:
401
402##
403# @query-alarm-clock
404#
405# Return information about QEMU's alarm clock.
406#
407# Returns a @QemuAlarmClock instance describing the alarm clock method
408# being currently used by QEMU (this is usually set by the '-clock'
409# command-line option).
410#
411# Since: 1.0
412##
413{ 'command': 'query-alarm-clock', 'returns': 'QemuAlarmClock' }
414
415Notice the "returns" keyword. As its name suggests, it's used to define the
416data returned by a command.
417
418It's time to implement the qmp_query_alarm_clock() function, you can put it
419in the qemu-timer.c file:
420
421QemuAlarmClock *qmp_query_alarm_clock(Error **errp)
422{
423 QemuAlarmClock *clock;
424 int64_t deadline;
425
426 clock = g_malloc0(sizeof(*clock));
427
428 deadline = qemu_next_alarm_deadline();
429 if (deadline > 0) {
430 clock->has_next_deadline = true;
431 clock->next_deadline = deadline;
432 }
433 clock->clock_name = g_strdup(alarm_timer->name);
434
435 return clock;
436}
437
438There are a number of things to be noticed:
439
4401. The QemuAlarmClock type is automatically generated by the QAPI framework,
441 its members correspond to the type's specification in the schema file
4422. As specified in the schema file, the function returns a QemuAlarmClock
443 instance and takes no arguments (besides the "errp" one, which is mandatory
444 for all QMP functions)
4453. The "clock" variable (which will point to our QAPI type instance) is
446 allocated by the regular g_malloc0() function. Note that we chose to
dabdf394 447 initialize the memory to zero. This is recommended for all QAPI types, as
4b389b5d
LC
448 it helps avoiding bad surprises (specially with booleans)
4494. Remember that "next_deadline" is optional? All optional members have a
450 'has_TYPE_NAME' member that should be properly set by the implementation,
451 as shown above
4525. Even static strings, such as "alarm_timer->name", should be dynamically
453 allocated by the implementation. This is so because the QAPI also generates
454 a function to free its types and it cannot distinguish between dynamically
455 or statically allocated strings
4566. You have to include the "qmp-commands.h" header file in qemu-timer.c,
457 otherwise qemu won't build
458
459The last step is to add the correspoding entry in the qmp-commands.hx file:
460
461 {
462 .name = "query-alarm-clock",
463 .args_type = "",
464 .mhandler.cmd_new = qmp_marshal_input_query_alarm_clock,
465 },
466
467Time to test the new command. Build qemu, run it as described in the "Testing"
468section and try this:
469
470{ "execute": "query-alarm-clock" }
471{
472 "return": {
473 "next-deadline": 2368219,
474 "clock-name": "dynticks"
475 }
476}
477
478==== The HMP command ====
479
480Here's the HMP counterpart of the query-alarm-clock command:
481
482void hmp_info_alarm_clock(Monitor *mon)
483{
484 QemuAlarmClock *clock;
e940f543 485 Error *err = NULL;
4b389b5d 486
e940f543
MA
487 clock = qmp_query_alarm_clock(&err);
488 if (err) {
4b389b5d 489 monitor_printf(mon, "Could not query alarm clock information\n");
e940f543 490 error_free(err);
4b389b5d
LC
491 return;
492 }
493
494 monitor_printf(mon, "Alarm clock method in use: '%s'\n", clock->clock_name);
495 if (clock->has_next_deadline) {
496 monitor_printf(mon, "Next alarm will fire in %" PRId64 " nanoseconds\n",
497 clock->next_deadline);
498 }
499
500 qapi_free_QemuAlarmClock(clock);
501}
502
503It's important to notice that hmp_info_alarm_clock() calls
504qapi_free_QemuAlarmClock() to free the data returned by qmp_query_alarm_clock().
505For user defined types, the QAPI will generate a qapi_free_QAPI_TYPE_NAME()
506function and that's what you have to use to free the types you define and
507qapi_free_QAPI_TYPE_NAMEList() for list types (explained in the next section).
508If the QMP call returns a string, then you should g_free() to free it.
509
510Also note that hmp_info_alarm_clock() performs error handling. That's not
511strictly required if you're sure the QMP function doesn't return errors, but
512it's good practice to always check for errors.
513
514Another important detail is that HMP's "info" commands don't go into the
515hmp-commands.hx. Instead, they go into the info_cmds[] table, which is defined
516in the monitor.c file. The entry for the "info alarmclock" follows:
517
518 {
519 .name = "alarmclock",
520 .args_type = "",
521 .params = "",
522 .help = "show information about the alarm clock",
523 .mhandler.info = hmp_info_alarm_clock,
524 },
525
526To test this, run qemu and type "info alarmclock" in the user monitor.
527
528=== Returning Lists ===
529
530For this example, we're going to return all available methods for the timer
531alarm, which is pretty much what the command-line option "-clock ?" does,
532except that we're also going to inform which method is in use.
533
534This first step is to define a new type:
535
536##
537# @TimerAlarmMethod
538#
539# Timer alarm method information.
540#
541# @method-name: The method's name.
542#
543# @current: true if this alarm method is currently in use, false otherwise
544#
545# Since: 1.0
546##
547{ 'type': 'TimerAlarmMethod',
548 'data': { 'method-name': 'str', 'current': 'bool' } }
549
550The command will be called "query-alarm-methods", here is its schema
551specification:
552
553##
554# @query-alarm-methods
555#
556# Returns information about available alarm methods.
557#
558# Returns: a list of @TimerAlarmMethod for each method
559#
560# Since: 1.0
561##
562{ 'command': 'query-alarm-methods', 'returns': ['TimerAlarmMethod'] }
563
564Notice the syntax for returning lists "'returns': ['TimerAlarmMethod']", this
565should be read as "returns a list of TimerAlarmMethod instances".
566
567The C implementation follows:
568
569TimerAlarmMethodList *qmp_query_alarm_methods(Error **errp)
570{
571 TimerAlarmMethodList *method_list = NULL;
572 const struct qemu_alarm_timer *p;
573 bool current = true;
574
575 for (p = alarm_timers; p->name; p++) {
576 TimerAlarmMethodList *info = g_malloc0(sizeof(*info));
577 info->value = g_malloc0(sizeof(*info->value));
578 info->value->method_name = g_strdup(p->name);
579 info->value->current = current;
580
581 current = false;
582
583 info->next = method_list;
584 method_list = info;
585 }
586
587 return method_list;
588}
589
590The most important difference from the previous examples is the
591TimerAlarmMethodList type, which is automatically generated by the QAPI from
592the TimerAlarmMethod type.
593
594Each list node is represented by a TimerAlarmMethodList instance. We have to
595allocate it, and that's done inside the for loop: the "info" pointer points to
596an allocated node. We also have to allocate the node's contents, which is
597stored in its "value" member. In our example, the "value" member is a pointer
598to an TimerAlarmMethod instance.
599
600Notice that the "current" variable is used as "true" only in the first
601interation of the loop. That's because the alarm timer method in use is the
602first element of the alarm_timers array. Also notice that QAPI lists are handled
603by hand and we return the head of the list.
604
605To test this you have to add the corresponding qmp-commands.hx entry:
606
607 {
608 .name = "query-alarm-methods",
609 .args_type = "",
610 .mhandler.cmd_new = qmp_marshal_input_query_alarm_methods,
611 },
612
613Now Build qemu, run it as explained in the "Testing" section and try our new
614command:
615
616{ "execute": "query-alarm-methods" }
617{
618 "return": [
619 {
620 "current": false,
621 "method-name": "unix"
622 },
623 {
624 "current": true,
625 "method-name": "dynticks"
626 }
627 ]
628}
629
630The HMP counterpart is a bit more complex than previous examples because it
631has to traverse the list, it's shown below for reference:
632
633void hmp_info_alarm_methods(Monitor *mon)
634{
635 TimerAlarmMethodList *method_list, *method;
e940f543 636 Error *err = NULL;
4b389b5d 637
e940f543
MA
638 method_list = qmp_query_alarm_methods(&err);
639 if (err) {
4b389b5d 640 monitor_printf(mon, "Could not query alarm methods\n");
e940f543 641 error_free(err);
4b389b5d
LC
642 return;
643 }
644
645 for (method = method_list; method; method = method->next) {
646 monitor_printf(mon, "%c %s\n", method->value->current ? '*' : ' ',
647 method->value->method_name);
648 }
649
650 qapi_free_TimerAlarmMethodList(method_list);
651}