writing-qmp-commands.txt 19 KB

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