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 352Modelling data in QAPI 353~~~~~~~~~~~~~~~~~~~~~~ 354 355For a QMP command that to be considered stable and supported long term, 356there is a requirement returned data should be explicitly modelled 357using fine-grained QAPI types. As a general guide, a caller of the QMP 358command should never need to parse individual returned data fields. If 359a field appears to need parsing, then it should be split into separate 360fields corresponding to each distinct data item. This should be the 361common case for any new QMP command that is intended to be used by 362machines, as opposed to exclusively human operators. 363 364Some QMP commands, however, are only intended as ad hoc debugging aids 365for human operators. While they may return large amounts of formatted 366data, it is not expected that machines will need to parse the result. 367The overhead of defining a fine grained QAPI type for the data may not 368be justified by the potential benefit. In such cases, it is permitted 369to have a command return a simple string that contains formatted data, 370however, it is mandatory for the command to use the 'x-' name prefix. 371This indicates that the command is not guaranteed to be long term 372stable / liable to change in future and is not following QAPI design 373best practices. An example where this approach is taken is the QMP 374command "x-query-registers". This returns a formatted dump of the 375architecture specific CPU state. The way the data is formatted varies 376across QEMU targets, is liable to change over time, and is only 377intended to be consumed as an opaque string by machines. 378 379User Defined Types 380~~~~~~~~~~~~~~~~~~ 381 382FIXME This example needs to be redone after commit 6d32717 383 384For this example we will write the query-alarm-clock command, which returns 385information about QEMU's timer alarm. For more information about it, please 386check the "-clock" command-line option. 387 388We want to return two pieces of information. The first one is the alarm clock's 389name. The second one is when the next alarm will fire. The former information is 390returned as a string, the latter is an integer in nanoseconds (which is not 391very useful in practice, as the timer has probably already fired when the 392information reaches the client). 393 394The best way to return that data is to create a new QAPI type, as shown below:: 395 396 ## 397 # @QemuAlarmClock 398 # 399 # QEMU alarm clock information. 400 # 401 # @clock-name: The alarm clock method's name. 402 # 403 # @next-deadline: The time (in nanoseconds) the next alarm will fire. 404 # 405 # Since: 1.0 406 ## 407 { 'type': 'QemuAlarmClock', 408 'data': { 'clock-name': 'str', '*next-deadline': 'int' } } 409 410The "type" keyword defines a new QAPI type. Its "data" member contains the 411type's members. In this example our members are the "clock-name" and the 412"next-deadline" one, which is optional. 413 414Now let's define the query-alarm-clock command:: 415 416 ## 417 # @query-alarm-clock 418 # 419 # Return information about QEMU's alarm clock. 420 # 421 # Returns a @QemuAlarmClock instance describing the alarm clock method 422 # being currently used by QEMU (this is usually set by the '-clock' 423 # command-line option). 424 # 425 # Since: 1.0 426 ## 427 { 'command': 'query-alarm-clock', 'returns': 'QemuAlarmClock' } 428 429Notice the "returns" keyword. As its name suggests, it's used to define the 430data returned by a command. 431 432It's time to implement the qmp_query_alarm_clock() function, you can put it 433in the qemu-timer.c file:: 434 435 QemuAlarmClock *qmp_query_alarm_clock(Error **errp) 436 { 437 QemuAlarmClock *clock; 438 int64_t deadline; 439 440 clock = g_malloc0(sizeof(*clock)); 441 442 deadline = qemu_next_alarm_deadline(); 443 if (deadline > 0) { 444 clock->has_next_deadline = true; 445 clock->next_deadline = deadline; 446 } 447 clock->clock_name = g_strdup(alarm_timer->name); 448 449 return clock; 450 } 451 452There are a number of things to be noticed: 453 4541. The QemuAlarmClock type is automatically generated by the QAPI framework, 455 its members correspond to the type's specification in the schema file 4562. As specified in the schema file, the function returns a QemuAlarmClock 457 instance and takes no arguments (besides the "errp" one, which is mandatory 458 for all QMP functions) 4593. The "clock" variable (which will point to our QAPI type instance) is 460 allocated by the regular g_malloc0() function. Note that we chose to 461 initialize the memory to zero. This is recommended for all QAPI types, as 462 it helps avoiding bad surprises (specially with booleans) 4634. Remember that "next_deadline" is optional? All optional members have a 464 'has_TYPE_NAME' member that should be properly set by the implementation, 465 as shown above 4665. Even static strings, such as "alarm_timer->name", should be dynamically 467 allocated by the implementation. This is so because the QAPI also generates 468 a function to free its types and it cannot distinguish between dynamically 469 or statically allocated strings 4706. You have to include "qapi/qapi-commands-misc.h" in qemu-timer.c 471 472Time to test the new command. Build qemu, run it as described in the "Testing" 473section and try this:: 474 475 { "execute": "query-alarm-clock" } 476 { 477 "return": { 478 "next-deadline": 2368219, 479 "clock-name": "dynticks" 480 } 481 } 482 483 484The HMP command 485~~~~~~~~~~~~~~~ 486 487Here's the HMP counterpart of the query-alarm-clock command:: 488 489 void hmp_info_alarm_clock(Monitor *mon) 490 { 491 QemuAlarmClock *clock; 492 Error *err = NULL; 493 494 clock = qmp_query_alarm_clock(&err); 495 if (hmp_handle_error(mon, err)) { 496 return; 497 } 498 499 monitor_printf(mon, "Alarm clock method in use: '%s'\n", clock->clock_name); 500 if (clock->has_next_deadline) { 501 monitor_printf(mon, "Next alarm will fire in %" PRId64 " nanoseconds\n", 502 clock->next_deadline); 503 } 504 505 qapi_free_QemuAlarmClock(clock); 506 } 507 508It's important to notice that hmp_info_alarm_clock() calls 509qapi_free_QemuAlarmClock() to free the data returned by qmp_query_alarm_clock(). 510For user defined types, the QAPI will generate a qapi_free_QAPI_TYPE_NAME() 511function and that's what you have to use to free the types you define and 512qapi_free_QAPI_TYPE_NAMEList() for list types (explained in the next section). 513If the QMP call returns a string, then you should g_free() to free it. 514 515Also note that hmp_info_alarm_clock() performs error handling. That's not 516strictly required if you're sure the QMP function doesn't return errors, but 517it's good practice to always check for errors. 518 519Another important detail is that HMP's "info" commands don't go into the 520hmp-commands.hx. Instead, they go into the info_cmds[] table, which is defined 521in the monitor/misc.c file. The entry for the "info alarmclock" follows:: 522 523 { 524 .name = "alarmclock", 525 .args_type = "", 526 .params = "", 527 .help = "show information about the alarm clock", 528 .cmd = hmp_info_alarm_clock, 529 }, 530 531To test this, run qemu and type "info alarmclock" in the user monitor. 532 533 534Returning Lists 535~~~~~~~~~~~~~~~ 536 537For this example, we're going to return all available methods for the timer 538alarm, which is pretty much what the command-line option "-clock ?" does, 539except that we're also going to inform which method is in use. 540 541This first step is to define a new type:: 542 543 ## 544 # @TimerAlarmMethod 545 # 546 # Timer alarm method information. 547 # 548 # @method-name: The method's name. 549 # 550 # @current: true if this alarm method is currently in use, false otherwise 551 # 552 # Since: 1.0 553 ## 554 { 'type': 'TimerAlarmMethod', 555 'data': { 'method-name': 'str', 'current': 'bool' } } 556 557The command will be called "query-alarm-methods", here is its schema 558specification:: 559 560 ## 561 # @query-alarm-methods 562 # 563 # Returns information about available alarm methods. 564 # 565 # Returns: a list of @TimerAlarmMethod for each method 566 # 567 # Since: 1.0 568 ## 569 { 'command': 'query-alarm-methods', 'returns': ['TimerAlarmMethod'] } 570 571Notice the syntax for returning lists "'returns': ['TimerAlarmMethod']", this 572should be read as "returns a list of TimerAlarmMethod instances". 573 574The C implementation follows:: 575 576 TimerAlarmMethodList *qmp_query_alarm_methods(Error **errp) 577 { 578 TimerAlarmMethodList *method_list = NULL; 579 const struct qemu_alarm_timer *p; 580 bool current = true; 581 582 for (p = alarm_timers; p->name; p++) { 583 TimerAlarmMethod *value = g_malloc0(*value); 584 value->method_name = g_strdup(p->name); 585 value->current = current; 586 QAPI_LIST_PREPEND(method_list, value); 587 current = false; 588 } 589 590 return method_list; 591 } 592 593The most important difference from the previous examples is the 594TimerAlarmMethodList type, which is automatically generated by the QAPI from 595the TimerAlarmMethod type. 596 597Each list node is represented by a TimerAlarmMethodList instance. We have to 598allocate it, and that's done inside the for loop: the "info" pointer points to 599an allocated node. We also have to allocate the node's contents, which is 600stored in its "value" member. In our example, the "value" member is a pointer 601to an TimerAlarmMethod instance. 602 603Notice that the "current" variable is used as "true" only in the first 604iteration of the loop. That's because the alarm timer method in use is the 605first element of the alarm_timers array. Also notice that QAPI lists are handled 606by hand and we return the head of the list. 607 608Now Build qemu, run it as explained in the "Testing" section and try our new 609command:: 610 611 { "execute": "query-alarm-methods" } 612 { 613 "return": [ 614 { 615 "current": false, 616 "method-name": "unix" 617 }, 618 { 619 "current": true, 620 "method-name": "dynticks" 621 } 622 ] 623 } 624 625The HMP counterpart is a bit more complex than previous examples because it 626has to traverse the list, it's shown below for reference:: 627 628 void hmp_info_alarm_methods(Monitor *mon) 629 { 630 TimerAlarmMethodList *method_list, *method; 631 Error *err = NULL; 632 633 method_list = qmp_query_alarm_methods(&err); 634 if (hmp_handle_error(mon, err)) { 635 return; 636 } 637 638 for (method = method_list; method; method = method->next) { 639 monitor_printf(mon, "%c %s\n", method->value->current ? '*' : ' ', 640 method->value->method_name); 641 } 642 643 qapi_free_TimerAlarmMethodList(method_list); 644 } 645