writing-qmp-commands.txt 21 KB

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