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