writing-qmp-commands.txt 19 KB

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