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