util/uuid: Define UUID_STR_LEN from UUID_NONE string
[qemu/kevin.git] / docs / devel / writing-monitor-commands.rst
blob2c11e71665198c555332bd9df236bca6b034be8d
1 How to write monitor commands
2 =============================
4 This document is a step-by-step guide on how to write new QMP commands using
5 the QAPI framework and HMP commands.
7 This document doesn't discuss QMP protocol level details, nor does it dive
8 into the QAPI framework implementation.
10 For an in-depth introduction to the QAPI framework, please refer to
11 docs/devel/qapi-code-gen.txt. For documentation about the QMP protocol,
12 start with docs/interop/qmp-intro.txt.
14 New commands may be implemented in QMP only.  New HMP commands should be
15 implemented on top of QMP.  The typical HMP command wraps around an
16 equivalent QMP command, but HMP convenience commands built from QMP
17 building blocks are also fine.  The long term goal is to make all
18 existing HMP commands conform to this, to fully isolate HMP from the
19 internals of QEMU. Refer to the `Writing a debugging aid returning
20 unstructured text`_ section for further guidance on commands that
21 would have traditionally been HMP only.
23 Overview
24 --------
26 Generally speaking, the following steps should be taken in order to write a
27 new QMP command.
29 1. Define the command and any types it needs in the appropriate QAPI
30    schema module.
32 2. Write the QMP command itself, which is a regular C function. Preferably,
33    the command should be exported by some QEMU subsystem. But it can also be
34    added to the monitor/qmp-cmds.c file
36 3. At this point the command can be tested under the QMP protocol
38 4. Write the HMP command equivalent. This is not required and should only be
39    done if it does make sense to have the functionality in HMP. The HMP command
40    is implemented in terms of the QMP command
42 The following sections will demonstrate each of the steps above. We will start
43 very simple and get more complex as we progress.
46 Testing
47 -------
49 For all the examples in the next sections, the test setup is the same and is
50 shown here.
52 First, QEMU should be started like this::
54  # qemu-system-TARGET [...] \
55      -chardev socket,id=qmp,port=4444,host=localhost,server=on \
56      -mon chardev=qmp,mode=control,pretty=on
58 Then, in a different terminal::
60  $ telnet localhost 4444
61  Trying 127.0.0.1...
62  Connected to localhost.
63  Escape character is '^]'.
64  {
65      "QMP": {
66          "version": {
67              "qemu": {
68                  "micro": 50,
69                  "minor": 15,
70                  "major": 0
71              },
72              "package": ""
73          },
74          "capabilities": [
75          ]
76      }
77  }
79 The above output is the QMP server saying you're connected. The server is
80 actually in capabilities negotiation mode. To enter in command mode type::
82  { "execute": "qmp_capabilities" }
84 Then the server should respond::
86  {
87      "return": {
88      }
89  }
91 Which is QMP's way of saying "the latest command executed OK and didn't return
92 any data". Now you're ready to enter the QMP example commands as explained in
93 the following sections.
96 Writing a simple command: hello-world
97 -------------------------------------
99 That's the most simple QMP command that can be written. Usually, this kind of
100 command carries some meaningful action in QEMU but here it will just print
101 "Hello, world" to the standard output.
103 Our command will be called "hello-world". It takes no arguments, nor does it
104 return any data.
106 The first step is defining the command in the appropriate QAPI schema
107 module.  We pick module qapi/misc.json, and add the following line at
108 the bottom::
110  { 'command': 'hello-world' }
112 The "command" keyword defines a new QMP command. It's an JSON object. All
113 schema entries are JSON objects. The line above will instruct the QAPI to
114 generate any prototypes and the necessary code to marshal and unmarshal
115 protocol data.
117 The next step is to write the "hello-world" implementation. As explained
118 earlier, it's preferable for commands to live in QEMU subsystems. But
119 "hello-world" doesn't pertain to any, so we put its implementation in
120 monitor/qmp-cmds.c::
122  void qmp_hello_world(Error **errp)
124      printf("Hello, world!\n");
127 There are a few things to be noticed:
129 1. QMP command implementation functions must be prefixed with "qmp\_"
130 2. qmp_hello_world() returns void, this is in accordance with the fact that the
131    command doesn't return any data
132 3. It takes an "Error \*\*" argument. This is required. Later we will see how to
133    return errors and take additional arguments. The Error argument should not
134    be touched if the command doesn't return errors
135 4. We won't add the function's prototype. That's automatically done by the QAPI
136 5. Printing to the terminal is discouraged for QMP commands, we do it here
137    because it's the easiest way to demonstrate a QMP command
139 You're done. Now build qemu, run it as suggested in the "Testing" section,
140 and then type the following QMP command::
142  { "execute": "hello-world" }
144 Then check the terminal running qemu and look for the "Hello, world" string. If
145 you don't see it then something went wrong.
148 Arguments
149 ~~~~~~~~~
151 Let's add an argument called "message" to our "hello-world" command. The new
152 argument will contain the string to be printed to stdout. It's an optional
153 argument, if it's not present we print our default "Hello, World" string.
155 The first change we have to do is to modify the command specification in the
156 schema file to the following::
158  { 'command': 'hello-world', 'data': { '*message': 'str' } }
160 Notice the new 'data' member in the schema. It's an JSON object whose each
161 element is an argument to the command in question. Also notice the asterisk,
162 it's used to mark the argument optional (that means that you shouldn't use it
163 for mandatory arguments). Finally, 'str' is the argument's type, which
164 stands for "string". The QAPI also supports integers, booleans, enumerations
165 and user defined types.
167 Now, let's update our C implementation in monitor/qmp-cmds.c::
169  void qmp_hello_world(const char *message, Error **errp)
171      if (message) {
172          printf("%s\n", message);
173      } else {
174          printf("Hello, world\n");
175      }
178 There are two important details to be noticed:
180 1. All optional arguments are accompanied by a 'has\_' boolean, which is set
181    if the optional argument is present or false otherwise
182 2. The C implementation signature must follow the schema's argument ordering,
183    which is defined by the "data" member
185 Time to test our new version of the "hello-world" command. Build qemu, run it as
186 described in the "Testing" section and then send two commands::
188  { "execute": "hello-world" }
190      "return": {
191      }
194  { "execute": "hello-world", "arguments": { "message": "We love qemu" } }
196      "return": {
197      }
200 You should see "Hello, world" and "We love qemu" in the terminal running qemu,
201 if you don't see these strings, then something went wrong.
204 Errors
205 ~~~~~~
207 QMP commands should use the error interface exported by the error.h header
208 file. Basically, most errors are set by calling the error_setg() function.
210 Let's say we don't accept the string "message" to contain the word "love". If
211 it does contain it, we want the "hello-world" command to return an error::
213  void qmp_hello_world(const char *message, Error **errp)
215      if (message) {
216          if (strstr(message, "love")) {
217              error_setg(errp, "the word 'love' is not allowed");
218              return;
219          }
220          printf("%s\n", message);
221      } else {
222          printf("Hello, world\n");
223      }
226 The first argument to the error_setg() function is the Error pointer
227 to pointer, which is passed to all QMP functions. The next argument is a human
228 description of the error, this is a free-form printf-like string.
230 Let's test the example above. Build qemu, run it as defined in the "Testing"
231 section, and then issue the following command::
233  { "execute": "hello-world", "arguments": { "message": "all you need is love" } }
235 The QMP server's response should be::
238      "error": {
239          "class": "GenericError",
240          "desc": "the word 'love' is not allowed"
241      }
244 Note that error_setg() produces a "GenericError" class.  In general,
245 all QMP errors should have that error class.  There are two exceptions
246 to this rule:
248  1. To support a management application's need to recognize a specific
249     error for special handling
251  2. Backward compatibility
253 If the failure you want to report falls into one of the two cases above,
254 use error_set() with a second argument of an ErrorClass value.
257 Command Documentation
258 ~~~~~~~~~~~~~~~~~~~~~
260 There's only one step missing to make "hello-world"'s implementation complete,
261 and that's its documentation in the schema file.
263 There are many examples of such documentation in the schema file already, but
264 here goes "hello-world"'s new entry for qapi/misc.json::
266  ##
267  # @hello-world:
269  # Print a client provided string to the standard output stream.
271  # @message: string to be printed
273  # Returns: Nothing on success.
275  # Notes: if @message is not provided, the "Hello, world" string will
276  #        be printed instead
278  # Since: <next qemu stable release, eg. 1.0>
279  ##
280  { 'command': 'hello-world', 'data': { '*message': 'str' } }
282 Please, note that the "Returns" clause is optional if a command doesn't return
283 any data nor any errors.
286 Implementing the HMP command
287 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
289 Now that the QMP command is in place, we can also make it available in the human
290 monitor (HMP).
292 With the introduction of the QAPI, HMP commands make QMP calls. Most of the
293 time HMP commands are simple wrappers. All HMP commands implementation exist in
294 the monitor/hmp-cmds.c file.
296 Here's the implementation of the "hello-world" HMP command::
298  void hmp_hello_world(Monitor *mon, const QDict *qdict)
300      const char *message = qdict_get_try_str(qdict, "message");
301      Error *err = NULL;
303      qmp_hello_world(!!message, message, &err);
304      if (hmp_handle_error(mon, err)) {
305          return;
306      }
309 Also, you have to add the function's prototype to the hmp.h file.
311 There are three important points to be noticed:
313 1. The "mon" and "qdict" arguments are mandatory for all HMP functions. The
314    former is the monitor object. The latter is how the monitor passes
315    arguments entered by the user to the command implementation
316 2. hmp_hello_world() performs error checking. In this example we just call
317    hmp_handle_error() which prints a message to the user, but we could do
318    more, like taking different actions depending on the error
319    qmp_hello_world() returns
320 3. The "err" variable must be initialized to NULL before performing the
321    QMP call
323 There's one last step to actually make the command available to monitor users,
324 we should add it to the hmp-commands.hx file::
326     {
327         .name       = "hello-world",
328         .args_type  = "message:s?",
329         .params     = "hello-world [message]",
330         .help       = "Print message to the standard output",
331         .cmd        = hmp_hello_world,
332     },
334  SRST
335  ``hello_world`` *message*
336    Print message to the standard output
337  ERST
339 To test this you have to open a user monitor and issue the "hello-world"
340 command. It might be instructive to check the command's documentation with
341 HMP's "help" command.
343 Please, check the "-monitor" command-line option to know how to open a user
344 monitor.
347 Writing more complex commands
348 -----------------------------
350 A QMP command is capable of returning any data the QAPI supports like integers,
351 strings, booleans, enumerations and user defined types.
353 In this section we will focus on user defined types. Please, check the QAPI
354 documentation for information about the other types.
357 Modelling data in QAPI
358 ~~~~~~~~~~~~~~~~~~~~~~
360 For a QMP command that to be considered stable and supported long term,
361 there is a requirement returned data should be explicitly modelled
362 using fine-grained QAPI types. As a general guide, a caller of the QMP
363 command should never need to parse individual returned data fields. If
364 a field appears to need parsing, then it should be split into separate
365 fields corresponding to each distinct data item. This should be the
366 common case for any new QMP command that is intended to be used by
367 machines, as opposed to exclusively human operators.
369 Some QMP commands, however, are only intended as ad hoc debugging aids
370 for human operators. While they may return large amounts of formatted
371 data, it is not expected that machines will need to parse the result.
372 The overhead of defining a fine grained QAPI type for the data may not
373 be justified by the potential benefit. In such cases, it is permitted
374 to have a command return a simple string that contains formatted data,
375 however, it is mandatory for the command to use the 'x-' name prefix.
376 This indicates that the command is not guaranteed to be long term
377 stable / liable to change in future and is not following QAPI design
378 best practices. An example where this approach is taken is the QMP
379 command "x-query-registers". This returns a formatted dump of the
380 architecture specific CPU state. The way the data is formatted varies
381 across QEMU targets, is liable to change over time, and is only
382 intended to be consumed as an opaque string by machines. Refer to the
383 `Writing a debugging aid returning unstructured text`_ section for
384 an illustration.
386 User Defined Types
387 ~~~~~~~~~~~~~~~~~~
389 FIXME This example needs to be redone after commit 6d32717
391 For this example we will write the query-alarm-clock command, which returns
392 information about QEMU's timer alarm. For more information about it, please
393 check the "-clock" command-line option.
395 We want to return two pieces of information. The first one is the alarm clock's
396 name. The second one is when the next alarm will fire. The former information is
397 returned as a string, the latter is an integer in nanoseconds (which is not
398 very useful in practice, as the timer has probably already fired when the
399 information reaches the client).
401 The best way to return that data is to create a new QAPI type, as shown below::
403  ##
404  # @QemuAlarmClock
406  # QEMU alarm clock information.
408  # @clock-name: The alarm clock method's name.
410  # @next-deadline: The time (in nanoseconds) the next alarm will fire.
412  # Since: 1.0
413  ##
414  { 'type': 'QemuAlarmClock',
415    'data': { 'clock-name': 'str', '*next-deadline': 'int' } }
417 The "type" keyword defines a new QAPI type. Its "data" member contains the
418 type's members. In this example our members are the "clock-name" and the
419 "next-deadline" one, which is optional.
421 Now let's define the query-alarm-clock command::
423  ##
424  # @query-alarm-clock
426  # Return information about QEMU's alarm clock.
428  # Returns a @QemuAlarmClock instance describing the alarm clock method
429  # being currently used by QEMU (this is usually set by the '-clock'
430  # command-line option).
432  # Since: 1.0
433  ##
434  { 'command': 'query-alarm-clock', 'returns': 'QemuAlarmClock' }
436 Notice the "returns" keyword. As its name suggests, it's used to define the
437 data returned by a command.
439 It's time to implement the qmp_query_alarm_clock() function, you can put it
440 in the qemu-timer.c file::
442  QemuAlarmClock *qmp_query_alarm_clock(Error **errp)
444      QemuAlarmClock *clock;
445      int64_t deadline;
447      clock = g_malloc0(sizeof(*clock));
449      deadline = qemu_next_alarm_deadline();
450      if (deadline > 0) {
451          clock->has_next_deadline = true;
452          clock->next_deadline = deadline;
453      }
454      clock->clock_name = g_strdup(alarm_timer->name);
456      return clock;
459 There are a number of things to be noticed:
461 1. The QemuAlarmClock type is automatically generated by the QAPI framework,
462    its members correspond to the type's specification in the schema file
463 2. As specified in the schema file, the function returns a QemuAlarmClock
464    instance and takes no arguments (besides the "errp" one, which is mandatory
465    for all QMP functions)
466 3. The "clock" variable (which will point to our QAPI type instance) is
467    allocated by the regular g_malloc0() function. Note that we chose to
468    initialize the memory to zero. This is recommended for all QAPI types, as
469    it helps avoiding bad surprises (specially with booleans)
470 4. Remember that "next_deadline" is optional? Non-pointer optional
471    members have a 'has_TYPE_NAME' member that should be properly set
472    by the implementation, as shown above
473 5. Even static strings, such as "alarm_timer->name", should be dynamically
474    allocated by the implementation. This is so because the QAPI also generates
475    a function to free its types and it cannot distinguish between dynamically
476    or statically allocated strings
477 6. You have to include "qapi/qapi-commands-misc.h" in qemu-timer.c
479 Time to test the new command. Build qemu, run it as described in the "Testing"
480 section and try this::
482  { "execute": "query-alarm-clock" }
484      "return": {
485          "next-deadline": 2368219,
486          "clock-name": "dynticks"
487      }
491 The HMP command
492 ~~~~~~~~~~~~~~~
494 Here's the HMP counterpart of the query-alarm-clock command::
496  void hmp_info_alarm_clock(Monitor *mon)
498      QemuAlarmClock *clock;
499      Error *err = NULL;
501      clock = qmp_query_alarm_clock(&err);
502      if (hmp_handle_error(mon, err)) {
503          return;
504      }
506      monitor_printf(mon, "Alarm clock method in use: '%s'\n", clock->clock_name);
507      if (clock->has_next_deadline) {
508          monitor_printf(mon, "Next alarm will fire in %" PRId64 " nanoseconds\n",
509                         clock->next_deadline);
510      }
512     qapi_free_QemuAlarmClock(clock);
515 It's important to notice that hmp_info_alarm_clock() calls
516 qapi_free_QemuAlarmClock() to free the data returned by qmp_query_alarm_clock().
517 For user defined types, the QAPI will generate a qapi_free_QAPI_TYPE_NAME()
518 function and that's what you have to use to free the types you define and
519 qapi_free_QAPI_TYPE_NAMEList() for list types (explained in the next section).
520 If the QMP call returns a string, then you should g_free() to free it.
522 Also note that hmp_info_alarm_clock() performs error handling. That's not
523 strictly required if you're sure the QMP function doesn't return errors, but
524 it's good practice to always check for errors.
526 Another important detail is that HMP's "info" commands don't go into the
527 hmp-commands.hx. Instead, they go into the info_cmds[] table, which is defined
528 in the monitor/misc.c file. The entry for the "info alarmclock" follows::
530     {
531         .name       = "alarmclock",
532         .args_type  = "",
533         .params     = "",
534         .help       = "show information about the alarm clock",
535         .cmd        = hmp_info_alarm_clock,
536     },
538 To test this, run qemu and type "info alarmclock" in the user monitor.
541 Returning Lists
542 ~~~~~~~~~~~~~~~
544 For this example, we're going to return all available methods for the timer
545 alarm, which is pretty much what the command-line option "-clock ?" does,
546 except that we're also going to inform which method is in use.
548 This first step is to define a new type::
550  ##
551  # @TimerAlarmMethod
553  # Timer alarm method information.
555  # @method-name: The method's name.
557  # @current: true if this alarm method is currently in use, false otherwise
559  # Since: 1.0
560  ##
561  { 'type': 'TimerAlarmMethod',
562    'data': { 'method-name': 'str', 'current': 'bool' } }
564 The command will be called "query-alarm-methods", here is its schema
565 specification::
567  ##
568  # @query-alarm-methods
570  # Returns information about available alarm methods.
572  # Returns: a list of @TimerAlarmMethod for each method
574  # Since: 1.0
575  ##
576  { 'command': 'query-alarm-methods', 'returns': ['TimerAlarmMethod'] }
578 Notice the syntax for returning lists "'returns': ['TimerAlarmMethod']", this
579 should be read as "returns a list of TimerAlarmMethod instances".
581 The C implementation follows::
583  TimerAlarmMethodList *qmp_query_alarm_methods(Error **errp)
585      TimerAlarmMethodList *method_list = NULL;
586      const struct qemu_alarm_timer *p;
587      bool current = true;
589      for (p = alarm_timers; p->name; p++) {
590          TimerAlarmMethod *value = g_malloc0(*value);
591          value->method_name = g_strdup(p->name);
592          value->current = current;
593          QAPI_LIST_PREPEND(method_list, value);
594          current = false;
595      }
597      return method_list;
600 The most important difference from the previous examples is the
601 TimerAlarmMethodList type, which is automatically generated by the QAPI from
602 the TimerAlarmMethod type.
604 Each list node is represented by a TimerAlarmMethodList instance. We have to
605 allocate it, and that's done inside the for loop: the "info" pointer points to
606 an allocated node. We also have to allocate the node's contents, which is
607 stored in its "value" member. In our example, the "value" member is a pointer
608 to an TimerAlarmMethod instance.
610 Notice that the "current" variable is used as "true" only in the first
611 iteration of the loop. That's because the alarm timer method in use is the
612 first element of the alarm_timers array. Also notice that QAPI lists are handled
613 by hand and we return the head of the list.
615 Now Build qemu, run it as explained in the "Testing" section and try our new
616 command::
618  { "execute": "query-alarm-methods" }
620      "return": [
621          {
622              "current": false,
623              "method-name": "unix"
624          },
625          {
626              "current": true,
627              "method-name": "dynticks"
628          }
629      ]
632 The HMP counterpart is a bit more complex than previous examples because it
633 has to traverse the list, it's shown below for reference::
635  void hmp_info_alarm_methods(Monitor *mon)
637      TimerAlarmMethodList *method_list, *method;
638      Error *err = NULL;
640      method_list = qmp_query_alarm_methods(&err);
641      if (hmp_handle_error(mon, err)) {
642          return;
643      }
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      }
650      qapi_free_TimerAlarmMethodList(method_list);
653 Writing a debugging aid returning unstructured text
654 ---------------------------------------------------
656 As discussed in section `Modelling data in QAPI`_, it is required that
657 commands expecting machine usage be using fine-grained QAPI data types.
658 The exception to this rule applies when the command is solely intended
659 as a debugging aid and allows for returning unstructured text. This is
660 commonly needed for query commands that report aspects of QEMU's
661 internal state that are useful to human operators.
663 In this example we will consider a simplified variant of the HMP
664 command ``info roms``. Following the earlier rules, this command will
665 need to live under the ``x-`` name prefix, so its QMP implementation
666 will be called ``x-query-roms``. It will have no parameters and will
667 return a single text string::
669  { 'struct': 'HumanReadableText',
670    'data': { 'human-readable-text': 'str' } }
672  { 'command': 'x-query-roms',
673    'returns': 'HumanReadableText' }
675 The ``HumanReadableText`` struct is intended to be used for all
676 commands, under the ``x-`` name prefix that are returning unstructured
677 text targeted at humans. It should never be used for commands outside
678 the ``x-`` name prefix, as those should be using structured QAPI types.
680 Implementing the QMP command
681 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
683 The QMP implementation will typically involve creating a ``GString``
684 object and printing formatted data into it::
686  HumanReadableText *qmp_x_query_roms(Error **errp)
688      g_autoptr(GString) buf = g_string_new("");
689      Rom *rom;
691      QTAILQ_FOREACH(rom, &roms, next) {
692         g_string_append_printf("%s size=0x%06zx name=\"%s\"\n",
693                                memory_region_name(rom->mr),
694                                rom->romsize,
695                                rom->name);
696      }
698      return human_readable_text_from_str(buf);
702 Implementing the HMP command
703 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
705 Now that the QMP command is in place, we can also make it available in
706 the human monitor (HMP) as shown in previous examples. The HMP
707 implementations will all look fairly similar, as all they need do is
708 invoke the QMP command and then print the resulting text or error
709 message. Here's the implementation of the "info roms" HMP command::
711  void hmp_info_roms(Monitor *mon, const QDict *qdict)
713      Error err = NULL;
714      g_autoptr(HumanReadableText) info = qmp_x_query_roms(&err);
716      if (hmp_handle_error(mon, err)) {
717          return;
718      }
719      monitor_puts(mon, info->human_readable_text);
722 Also, you have to add the function's prototype to the hmp.h file.
724 There's one last step to actually make the command available to
725 monitor users, we should add it to the hmp-commands-info.hx file::
727     {
728         .name       = "roms",
729         .args_type  = "",
730         .params     = "",
731         .help       = "show roms",
732         .cmd        = hmp_info_roms,
733     },
735 The case of writing a HMP info handler that calls a no-parameter QMP query
736 command is quite common. To simplify the implementation there is a general
737 purpose HMP info handler for this scenario. All that is required to expose
738 a no-parameter QMP query command via HMP is to declare it using the
739 '.cmd_info_hrt' field to point to the QMP handler, and leave the '.cmd'
740 field NULL::
742     {
743         .name         = "roms",
744         .args_type    = "",
745         .params       = "",
746         .help         = "show roms",
747         .cmd_info_hrt = qmp_x_query_roms,
748     },