qemu/docs/devel/writing-qmp-commands.rst
<<
>>
Prefs
   1How to write QMP commands using the QAPI framework
   2==================================================
   3
   4This document is a step-by-step guide on how to write new QMP commands using
   5the QAPI framework. It also shows how to implement new style 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 command that doesn't return data
  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 (err) {
 297         monitor_printf(mon, "%s\n", error_get_pretty(err));
 298         error_free(err);
 299         return;
 300     }
 301 }
 302
 303Also, you have to add the function's prototype to the hmp.h file.
 304
 305There are three important points to be noticed:
 306
 3071. The "mon" and "qdict" arguments are mandatory for all HMP functions. The
 308   former is the monitor object. The latter is how the monitor passes
 309   arguments entered by the user to the command implementation
 3102. hmp_hello_world() performs error checking. In this example we just print
 311   the error description to the user, but we could do more, like taking
 312   different actions depending on the error qmp_hello_world() returns
 3133. The "err" variable must be initialized to NULL before performing the
 314   QMP call
 315
 316There's one last step to actually make the command available to monitor users,
 317we should add it to the hmp-commands.hx file::
 318
 319    {
 320        .name       = "hello-world",
 321        .args_type  = "message:s?",
 322        .params     = "hello-world [message]",
 323        .help       = "Print message to the standard output",
 324        .cmd        = hmp_hello_world,
 325    },
 326
 327::
 328
 329 STEXI
 330 @item hello_world @var{message}
 331 @findex hello_world
 332 Print message to the standard output
 333 ETEXI
 334
 335To test this you have to open a user monitor and issue the "hello-world"
 336command. It might be instructive to check the command's documentation with
 337HMP's "help" command.
 338
 339Please, check the "-monitor" command-line option to know how to open a user
 340monitor.
 341
 342
 343Writing a command that returns data
 344-----------------------------------
 345
 346A QMP command is capable of returning any data the QAPI supports like integers,
 347strings, booleans, enumerations and user defined types.
 348
 349In this section we will focus on user defined types. Please, check the QAPI
 350documentation for information about the other types.
 351
 352
 353User Defined Types
 354~~~~~~~~~~~~~~~~~~
 355
 356FIXME This example needs to be redone after commit 6d32717
 357
 358For this example we will write the query-alarm-clock command, which returns
 359information about QEMU's timer alarm. For more information about it, please
 360check the "-clock" command-line option.
 361
 362We want to return two pieces of information. The first one is the alarm clock's
 363name. The second one is when the next alarm will fire. The former information is
 364returned as a string, the latter is an integer in nanoseconds (which is not
 365very useful in practice, as the timer has probably already fired when the
 366information reaches the client).
 367
 368The best way to return that data is to create a new QAPI type, as shown below::
 369
 370 ##
 371 # @QemuAlarmClock
 372 #
 373 # QEMU alarm clock information.
 374 #
 375 # @clock-name: The alarm clock method's name.
 376 #
 377 # @next-deadline: The time (in nanoseconds) the next alarm will fire.
 378 #
 379 # Since: 1.0
 380 ##
 381 { 'type': 'QemuAlarmClock',
 382   'data': { 'clock-name': 'str', '*next-deadline': 'int' } }
 383
 384The "type" keyword defines a new QAPI type. Its "data" member contains the
 385type's members. In this example our members are the "clock-name" and the
 386"next-deadline" one, which is optional.
 387
 388Now let's define the query-alarm-clock command::
 389
 390 ##
 391 # @query-alarm-clock
 392 #
 393 # Return information about QEMU's alarm clock.
 394 #
 395 # Returns a @QemuAlarmClock instance describing the alarm clock method
 396 # being currently used by QEMU (this is usually set by the '-clock'
 397 # command-line option).
 398 #
 399 # Since: 1.0
 400 ##
 401 { 'command': 'query-alarm-clock', 'returns': 'QemuAlarmClock' }
 402
 403Notice the "returns" keyword. As its name suggests, it's used to define the
 404data returned by a command.
 405
 406It's time to implement the qmp_query_alarm_clock() function, you can put it
 407in the qemu-timer.c file::
 408
 409 QemuAlarmClock *qmp_query_alarm_clock(Error **errp)
 410 {
 411     QemuAlarmClock *clock;
 412     int64_t deadline;
 413
 414     clock = g_malloc0(sizeof(*clock));
 415
 416     deadline = qemu_next_alarm_deadline();
 417     if (deadline > 0) {
 418         clock->has_next_deadline = true;
 419         clock->next_deadline = deadline;
 420     }
 421     clock->clock_name = g_strdup(alarm_timer->name);
 422
 423     return clock;
 424 }
 425
 426There are a number of things to be noticed:
 427
 4281. The QemuAlarmClock type is automatically generated by the QAPI framework,
 429   its members correspond to the type's specification in the schema file
 4302. As specified in the schema file, the function returns a QemuAlarmClock
 431   instance and takes no arguments (besides the "errp" one, which is mandatory
 432   for all QMP functions)
 4333. The "clock" variable (which will point to our QAPI type instance) is
 434   allocated by the regular g_malloc0() function. Note that we chose to
 435   initialize the memory to zero. This is recommended for all QAPI types, as
 436   it helps avoiding bad surprises (specially with booleans)
 4374. Remember that "next_deadline" is optional? All optional members have a
 438   'has_TYPE_NAME' member that should be properly set by the implementation,
 439   as shown above
 4405. Even static strings, such as "alarm_timer->name", should be dynamically
 441   allocated by the implementation. This is so because the QAPI also generates
 442   a function to free its types and it cannot distinguish between dynamically
 443   or statically allocated strings
 4446. You have to include "qapi/qapi-commands-misc.h" in qemu-timer.c
 445
 446Time to test the new command. Build qemu, run it as described in the "Testing"
 447section and try this::
 448
 449 { "execute": "query-alarm-clock" }
 450 {
 451     "return": {
 452         "next-deadline": 2368219,
 453         "clock-name": "dynticks"
 454     }
 455 }
 456
 457
 458The HMP command
 459~~~~~~~~~~~~~~~
 460
 461Here's the HMP counterpart of the query-alarm-clock command::
 462
 463 void hmp_info_alarm_clock(Monitor *mon)
 464 {
 465     QemuAlarmClock *clock;
 466     Error *err = NULL;
 467
 468     clock = qmp_query_alarm_clock(&err);
 469     if (err) {
 470         monitor_printf(mon, "Could not query alarm clock information\n");
 471         error_free(err);
 472         return;
 473     }
 474
 475     monitor_printf(mon, "Alarm clock method in use: '%s'\n", clock->clock_name);
 476     if (clock->has_next_deadline) {
 477         monitor_printf(mon, "Next alarm will fire in %" PRId64 " nanoseconds\n",
 478                        clock->next_deadline);
 479     }
 480
 481    qapi_free_QemuAlarmClock(clock);
 482 }
 483
 484It's important to notice that hmp_info_alarm_clock() calls
 485qapi_free_QemuAlarmClock() to free the data returned by qmp_query_alarm_clock().
 486For user defined types, the QAPI will generate a qapi_free_QAPI_TYPE_NAME()
 487function and that's what you have to use to free the types you define and
 488qapi_free_QAPI_TYPE_NAMEList() for list types (explained in the next section).
 489If the QMP call returns a string, then you should g_free() to free it.
 490
 491Also note that hmp_info_alarm_clock() performs error handling. That's not
 492strictly required if you're sure the QMP function doesn't return errors, but
 493it's good practice to always check for errors.
 494
 495Another important detail is that HMP's "info" commands don't go into the
 496hmp-commands.hx. Instead, they go into the info_cmds[] table, which is defined
 497in the monitor/misc.c file. The entry for the "info alarmclock" follows::
 498
 499    {
 500        .name       = "alarmclock",
 501        .args_type  = "",
 502        .params     = "",
 503        .help       = "show information about the alarm clock",
 504        .cmd        = hmp_info_alarm_clock,
 505    },
 506
 507To test this, run qemu and type "info alarmclock" in the user monitor.
 508
 509
 510Returning Lists
 511~~~~~~~~~~~~~~~
 512
 513For this example, we're going to return all available methods for the timer
 514alarm, which is pretty much what the command-line option "-clock ?" does,
 515except that we're also going to inform which method is in use.
 516
 517This first step is to define a new type::
 518
 519 ##
 520 # @TimerAlarmMethod
 521 #
 522 # Timer alarm method information.
 523 #
 524 # @method-name: The method's name.
 525 #
 526 # @current: true if this alarm method is currently in use, false otherwise
 527 #
 528 # Since: 1.0
 529 ##
 530 { 'type': 'TimerAlarmMethod',
 531   'data': { 'method-name': 'str', 'current': 'bool' } }
 532
 533The command will be called "query-alarm-methods", here is its schema
 534specification::
 535
 536 ##
 537 # @query-alarm-methods
 538 #
 539 # Returns information about available alarm methods.
 540 #
 541 # Returns: a list of @TimerAlarmMethod for each method
 542 #
 543 # Since: 1.0
 544 ##
 545 { 'command': 'query-alarm-methods', 'returns': ['TimerAlarmMethod'] }
 546
 547Notice the syntax for returning lists "'returns': ['TimerAlarmMethod']", this
 548should be read as "returns a list of TimerAlarmMethod instances".
 549
 550The C implementation follows::
 551
 552 TimerAlarmMethodList *qmp_query_alarm_methods(Error **errp)
 553 {
 554     TimerAlarmMethodList *method_list = NULL;
 555     const struct qemu_alarm_timer *p;
 556     bool current = true;
 557
 558     for (p = alarm_timers; p->name; p++) {
 559         TimerAlarmMethod *value = g_malloc0(*value);
 560         value->method_name = g_strdup(p->name);
 561         value->current = current;
 562         QAPI_LIST_PREPEND(method_list, value);
 563         current = false;
 564     }
 565
 566     return method_list;
 567 }
 568
 569The most important difference from the previous examples is the
 570TimerAlarmMethodList type, which is automatically generated by the QAPI from
 571the TimerAlarmMethod type.
 572
 573Each list node is represented by a TimerAlarmMethodList instance. We have to
 574allocate it, and that's done inside the for loop: the "info" pointer points to
 575an allocated node. We also have to allocate the node's contents, which is
 576stored in its "value" member. In our example, the "value" member is a pointer
 577to an TimerAlarmMethod instance.
 578
 579Notice that the "current" variable is used as "true" only in the first
 580iteration of the loop. That's because the alarm timer method in use is the
 581first element of the alarm_timers array. Also notice that QAPI lists are handled
 582by hand and we return the head of the list.
 583
 584Now Build qemu, run it as explained in the "Testing" section and try our new
 585command::
 586
 587 { "execute": "query-alarm-methods" }
 588 {
 589     "return": [
 590         {
 591             "current": false,
 592             "method-name": "unix"
 593         },
 594         {
 595             "current": true,
 596             "method-name": "dynticks"
 597         }
 598     ]
 599 }
 600
 601The HMP counterpart is a bit more complex than previous examples because it
 602has to traverse the list, it's shown below for reference::
 603
 604 void hmp_info_alarm_methods(Monitor *mon)
 605 {
 606     TimerAlarmMethodList *method_list, *method;
 607     Error *err = NULL;
 608
 609     method_list = qmp_query_alarm_methods(&err);
 610     if (err) {
 611         monitor_printf(mon, "Could not query alarm methods\n");
 612         error_free(err);
 613         return;
 614     }
 615
 616     for (method = method_list; method; method = method->next) {
 617         monitor_printf(mon, "%c %s\n", method->value->current ? '*' : ' ',
 618                                        method->value->method_name);
 619     }
 620
 621     qapi_free_TimerAlarmMethodList(method_list);
 622 }
 623