2
0

writing-qmp-commands.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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. The basic function used to set an error is the error_set() one.
  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 the return the
  161. InvalidParameter error.
  162. Only one change is required, and it's in the C implementation:
  163. void qmp_hello_world(bool has_message, const char *message, Error **errp)
  164. {
  165. if (has_message) {
  166. if (strstr(message, "love")) {
  167. error_set(errp, QERR_INVALID_PARAMETER, "message");
  168. return;
  169. }
  170. printf("%s\n", message);
  171. } else {
  172. printf("Hello, world\n");
  173. }
  174. }
  175. Let's test it. Build qemu, run it as defined in the "Testing" section, and
  176. then issue the following command:
  177. { "execute": "hello-world", "arguments": { "message": "we love qemu" } }
  178. The QMP server's response should be:
  179. {
  180. "error": {
  181. "class": "InvalidParameter",
  182. "desc": "Invalid parameter 'message'",
  183. "data": {
  184. "name": "message"
  185. }
  186. }
  187. }
  188. Which is the InvalidParameter error.
  189. When you have to return an error but you're unsure what error to return or
  190. which arguments an error takes, you should look at the qerror.h file. Note
  191. that you might be required to add new errors if needed.
  192. FIXME: describe better the error API and how to add new errors.
  193. === Command Documentation ===
  194. There's only one step missing to make "hello-world"'s implementation complete,
  195. and that's its documentation in the schema file.
  196. This is very important. No QMP command will be accepted in QEMU without proper
  197. documentation.
  198. There are many examples of such documentation in the schema file already, but
  199. here goes "hello-world"'s new entry for the qapi-schema.json file:
  200. ##
  201. # @hello-world
  202. #
  203. # Print a client provided string to the standard output stream.
  204. #
  205. # @message: #optional string to be printed
  206. #
  207. # Returns: Nothing on success.
  208. # If @message contains "love", InvalidParameter
  209. #
  210. # Notes: if @message is not provided, the "Hello, world" string will
  211. # be printed instead
  212. #
  213. # Since: <next qemu stable release, eg. 1.0>
  214. ##
  215. { 'command': 'hello-world', 'data': { '*message': 'str' } }
  216. Please, note that the "Returns" clause is optional if a command doesn't return
  217. any data nor any errors.
  218. === Implementing the HMP command ===
  219. Now that the QMP command is in place, we can also make it available in the human
  220. monitor (HMP).
  221. With the introduction of the QAPI, HMP commands make QMP calls. Most of the
  222. time HMP commands are simple wrappers. All HMP commands implementation exist in
  223. the hmp.c file.
  224. Here's the implementation of the "hello-world" HMP command:
  225. void hmp_hello_world(Monitor *mon, const QDict *qdict)
  226. {
  227. const char *message = qdict_get_try_str(qdict, "message");
  228. Error *errp = NULL;
  229. qmp_hello_world(!!message, message, &errp);
  230. if (error_is_set(&errp)) {
  231. monitor_printf(mon, "%s\n", error_get_pretty(errp));
  232. error_free(errp);
  233. return;
  234. }
  235. }
  236. Also, you have to add the function's prototype to the hmp.h file.
  237. There are three important points to be noticed:
  238. 1. The "mon" and "qdict" arguments are mandatory for all HMP functions. The
  239. former is the monitor object. The latter is how the monitor passes
  240. arguments entered by the user to the command implementation
  241. 2. hmp_hello_world() performs error checking. In this example we just print
  242. the error description to the user, but we could do more, like taking
  243. different actions depending on the error qmp_hello_world() returns
  244. 3. The "errp" variable must be initialized to NULL before performing the
  245. QMP call
  246. There's one last step to actually make the command available to monitor users,
  247. we should add it to the hmp-commands.hx file:
  248. {
  249. .name = "hello-world",
  250. .args_type = "message:s?",
  251. .params = "hello-world [message]",
  252. .help = "Print message to the standard output",
  253. .mhandler.cmd = hmp_hello_world,
  254. },
  255. STEXI
  256. @item hello_world @var{message}
  257. @findex hello_world
  258. Print message to the standard output
  259. ETEXI
  260. To test this you have to open a user monitor and issue the "hello-world"
  261. command. It might be instructive to check the command's documentation with
  262. HMP's "help" command.
  263. Please, check the "-monitor" command-line option to know how to open a user
  264. monitor.
  265. == Writing a command that returns data ==
  266. A QMP command is capable of returning any data the QAPI supports like integers,
  267. strings, booleans, enumerations and user defined types.
  268. In this section we will focus on user defined types. Please, check the QAPI
  269. documentation for information about the other types.
  270. === User Defined Types ===
  271. For this example we will write the query-alarm-clock command, which returns
  272. information about QEMU's timer alarm. For more information about it, please
  273. check the "-clock" command-line option.
  274. We want to return two pieces of information. The first one is the alarm clock's
  275. name. The second one is when the next alarm will fire. The former information is
  276. returned as a string, the latter is an integer in nanoseconds (which is not
  277. very useful in practice, as the timer has probably already fired when the
  278. information reaches the client).
  279. The best way to return that data is to create a new QAPI type, as shown below:
  280. ##
  281. # @QemuAlarmClock
  282. #
  283. # QEMU alarm clock information.
  284. #
  285. # @clock-name: The alarm clock method's name.
  286. #
  287. # @next-deadline: #optional The time (in nanoseconds) the next alarm will fire.
  288. #
  289. # Since: 1.0
  290. ##
  291. { 'type': 'QemuAlarmClock',
  292. 'data': { 'clock-name': 'str', '*next-deadline': 'int' } }
  293. The "type" keyword defines a new QAPI type. Its "data" member contains the
  294. type's members. In this example our members are the "clock-name" and the
  295. "next-deadline" one, which is optional.
  296. Now let's define the query-alarm-clock command:
  297. ##
  298. # @query-alarm-clock
  299. #
  300. # Return information about QEMU's alarm clock.
  301. #
  302. # Returns a @QemuAlarmClock instance describing the alarm clock method
  303. # being currently used by QEMU (this is usually set by the '-clock'
  304. # command-line option).
  305. #
  306. # Since: 1.0
  307. ##
  308. { 'command': 'query-alarm-clock', 'returns': 'QemuAlarmClock' }
  309. Notice the "returns" keyword. As its name suggests, it's used to define the
  310. data returned by a command.
  311. It's time to implement the qmp_query_alarm_clock() function, you can put it
  312. in the qemu-timer.c file:
  313. QemuAlarmClock *qmp_query_alarm_clock(Error **errp)
  314. {
  315. QemuAlarmClock *clock;
  316. int64_t deadline;
  317. clock = g_malloc0(sizeof(*clock));
  318. deadline = qemu_next_alarm_deadline();
  319. if (deadline > 0) {
  320. clock->has_next_deadline = true;
  321. clock->next_deadline = deadline;
  322. }
  323. clock->clock_name = g_strdup(alarm_timer->name);
  324. return clock;
  325. }
  326. There are a number of things to be noticed:
  327. 1. The QemuAlarmClock type is automatically generated by the QAPI framework,
  328. its members correspond to the type's specification in the schema file
  329. 2. As specified in the schema file, the function returns a QemuAlarmClock
  330. instance and takes no arguments (besides the "errp" one, which is mandatory
  331. for all QMP functions)
  332. 3. The "clock" variable (which will point to our QAPI type instance) is
  333. allocated by the regular g_malloc0() function. Note that we chose to
  334. initialize the memory to zero. This is recommended for all QAPI types, as
  335. it helps avoiding bad surprises (specially with booleans)
  336. 4. Remember that "next_deadline" is optional? All optional members have a
  337. 'has_TYPE_NAME' member that should be properly set by the implementation,
  338. as shown above
  339. 5. Even static strings, such as "alarm_timer->name", should be dynamically
  340. allocated by the implementation. This is so because the QAPI also generates
  341. a function to free its types and it cannot distinguish between dynamically
  342. or statically allocated strings
  343. 6. You have to include the "qmp-commands.h" header file in qemu-timer.c,
  344. otherwise qemu won't build
  345. The last step is to add the correspoding entry in the qmp-commands.hx file:
  346. {
  347. .name = "query-alarm-clock",
  348. .args_type = "",
  349. .mhandler.cmd_new = qmp_marshal_input_query_alarm_clock,
  350. },
  351. Time to test the new command. Build qemu, run it as described in the "Testing"
  352. section and try this:
  353. { "execute": "query-alarm-clock" }
  354. {
  355. "return": {
  356. "next-deadline": 2368219,
  357. "clock-name": "dynticks"
  358. }
  359. }
  360. ==== The HMP command ====
  361. Here's the HMP counterpart of the query-alarm-clock command:
  362. void hmp_info_alarm_clock(Monitor *mon)
  363. {
  364. QemuAlarmClock *clock;
  365. Error *errp = NULL;
  366. clock = qmp_query_alarm_clock(&errp);
  367. if (error_is_set(&errp)) {
  368. monitor_printf(mon, "Could not query alarm clock information\n");
  369. error_free(errp);
  370. return;
  371. }
  372. monitor_printf(mon, "Alarm clock method in use: '%s'\n", clock->clock_name);
  373. if (clock->has_next_deadline) {
  374. monitor_printf(mon, "Next alarm will fire in %" PRId64 " nanoseconds\n",
  375. clock->next_deadline);
  376. }
  377. qapi_free_QemuAlarmClock(clock);
  378. }
  379. It's important to notice that hmp_info_alarm_clock() calls
  380. qapi_free_QemuAlarmClock() to free the data returned by qmp_query_alarm_clock().
  381. For user defined types, the QAPI will generate a qapi_free_QAPI_TYPE_NAME()
  382. function and that's what you have to use to free the types you define and
  383. qapi_free_QAPI_TYPE_NAMEList() for list types (explained in the next section).
  384. If the QMP call returns a string, then you should g_free() to free it.
  385. Also note that hmp_info_alarm_clock() performs error handling. That's not
  386. strictly required if you're sure the QMP function doesn't return errors, but
  387. it's good practice to always check for errors.
  388. Another important detail is that HMP's "info" commands don't go into the
  389. hmp-commands.hx. Instead, they go into the info_cmds[] table, which is defined
  390. in the monitor.c file. The entry for the "info alarmclock" follows:
  391. {
  392. .name = "alarmclock",
  393. .args_type = "",
  394. .params = "",
  395. .help = "show information about the alarm clock",
  396. .mhandler.info = hmp_info_alarm_clock,
  397. },
  398. To test this, run qemu and type "info alarmclock" in the user monitor.
  399. === Returning Lists ===
  400. For this example, we're going to return all available methods for the timer
  401. alarm, which is pretty much what the command-line option "-clock ?" does,
  402. except that we're also going to inform which method is in use.
  403. This first step is to define a new type:
  404. ##
  405. # @TimerAlarmMethod
  406. #
  407. # Timer alarm method information.
  408. #
  409. # @method-name: The method's name.
  410. #
  411. # @current: true if this alarm method is currently in use, false otherwise
  412. #
  413. # Since: 1.0
  414. ##
  415. { 'type': 'TimerAlarmMethod',
  416. 'data': { 'method-name': 'str', 'current': 'bool' } }
  417. The command will be called "query-alarm-methods", here is its schema
  418. specification:
  419. ##
  420. # @query-alarm-methods
  421. #
  422. # Returns information about available alarm methods.
  423. #
  424. # Returns: a list of @TimerAlarmMethod for each method
  425. #
  426. # Since: 1.0
  427. ##
  428. { 'command': 'query-alarm-methods', 'returns': ['TimerAlarmMethod'] }
  429. Notice the syntax for returning lists "'returns': ['TimerAlarmMethod']", this
  430. should be read as "returns a list of TimerAlarmMethod instances".
  431. The C implementation follows:
  432. TimerAlarmMethodList *qmp_query_alarm_methods(Error **errp)
  433. {
  434. TimerAlarmMethodList *method_list = NULL;
  435. const struct qemu_alarm_timer *p;
  436. bool current = true;
  437. for (p = alarm_timers; p->name; p++) {
  438. TimerAlarmMethodList *info = g_malloc0(sizeof(*info));
  439. info->value = g_malloc0(sizeof(*info->value));
  440. info->value->method_name = g_strdup(p->name);
  441. info->value->current = current;
  442. current = false;
  443. info->next = method_list;
  444. method_list = info;
  445. }
  446. return method_list;
  447. }
  448. The most important difference from the previous examples is the
  449. TimerAlarmMethodList type, which is automatically generated by the QAPI from
  450. the TimerAlarmMethod type.
  451. Each list node is represented by a TimerAlarmMethodList instance. We have to
  452. allocate it, and that's done inside the for loop: the "info" pointer points to
  453. an allocated node. We also have to allocate the node's contents, which is
  454. stored in its "value" member. In our example, the "value" member is a pointer
  455. to an TimerAlarmMethod instance.
  456. Notice that the "current" variable is used as "true" only in the first
  457. interation of the loop. That's because the alarm timer method in use is the
  458. first element of the alarm_timers array. Also notice that QAPI lists are handled
  459. by hand and we return the head of the list.
  460. To test this you have to add the corresponding qmp-commands.hx entry:
  461. {
  462. .name = "query-alarm-methods",
  463. .args_type = "",
  464. .mhandler.cmd_new = qmp_marshal_input_query_alarm_methods,
  465. },
  466. Now Build qemu, run it as explained in the "Testing" section and try our new
  467. command:
  468. { "execute": "query-alarm-methods" }
  469. {
  470. "return": [
  471. {
  472. "current": false,
  473. "method-name": "unix"
  474. },
  475. {
  476. "current": true,
  477. "method-name": "dynticks"
  478. }
  479. ]
  480. }
  481. The HMP counterpart is a bit more complex than previous examples because it
  482. has to traverse the list, it's shown below for reference:
  483. void hmp_info_alarm_methods(Monitor *mon)
  484. {
  485. TimerAlarmMethodList *method_list, *method;
  486. Error *errp = NULL;
  487. method_list = qmp_query_alarm_methods(&errp);
  488. if (error_is_set(&errp)) {
  489. monitor_printf(mon, "Could not query alarm methods\n");
  490. error_free(errp);
  491. return;
  492. }
  493. for (method = method_list; method; method = method->next) {
  494. monitor_printf(mon, "%c %s\n", method->value->current ? '*' : ' ',
  495. method->value->method_name);
  496. }
  497. qapi_free_TimerAlarmMethodList(method_list);
  498. }