qmp.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. /*
  2. * QEMU monitor
  3. *
  4. * Copyright (c) 2003-2004 Fabrice Bellard
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. #include "qemu/osdep.h"
  25. #include "chardev/char-io.h"
  26. #include "monitor-internal.h"
  27. #include "qapi/error.h"
  28. #include "qapi/qapi-commands-control.h"
  29. #include "qapi/qmp/qdict.h"
  30. #include "qapi/qmp/qjson.h"
  31. #include "qapi/qmp/qlist.h"
  32. #include "qapi/qmp/qstring.h"
  33. #include "trace.h"
  34. struct QMPRequest {
  35. /* Owner of the request */
  36. MonitorQMP *mon;
  37. /*
  38. * Request object to be handled or Error to be reported
  39. * (exactly one of them is non-null)
  40. */
  41. QObject *req;
  42. Error *err;
  43. };
  44. typedef struct QMPRequest QMPRequest;
  45. QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
  46. static bool qmp_oob_enabled(MonitorQMP *mon)
  47. {
  48. return mon->capab[QMP_CAPABILITY_OOB];
  49. }
  50. static void monitor_qmp_caps_reset(MonitorQMP *mon)
  51. {
  52. memset(mon->capab_offered, 0, sizeof(mon->capab_offered));
  53. memset(mon->capab, 0, sizeof(mon->capab));
  54. mon->capab_offered[QMP_CAPABILITY_OOB] = mon->common.use_io_thread;
  55. }
  56. static void qmp_request_free(QMPRequest *req)
  57. {
  58. qobject_unref(req->req);
  59. error_free(req->err);
  60. g_free(req);
  61. }
  62. /* Caller must hold mon->qmp.qmp_queue_lock */
  63. static void monitor_qmp_cleanup_req_queue_locked(MonitorQMP *mon)
  64. {
  65. while (!g_queue_is_empty(mon->qmp_requests)) {
  66. qmp_request_free(g_queue_pop_head(mon->qmp_requests));
  67. }
  68. }
  69. static void monitor_qmp_cleanup_queue_and_resume(MonitorQMP *mon)
  70. {
  71. qemu_mutex_lock(&mon->qmp_queue_lock);
  72. /*
  73. * Same condition as in monitor_qmp_bh_dispatcher(), but before
  74. * removing an element from the queue (hence no `- 1`).
  75. * Also, the queue should not be empty either, otherwise the
  76. * monitor hasn't been suspended yet (or was already resumed).
  77. */
  78. bool need_resume = (!qmp_oob_enabled(mon) ||
  79. mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX)
  80. && !g_queue_is_empty(mon->qmp_requests);
  81. monitor_qmp_cleanup_req_queue_locked(mon);
  82. if (need_resume) {
  83. /*
  84. * handle_qmp_command() suspended the monitor because the
  85. * request queue filled up, to be resumed when the queue has
  86. * space again. We just emptied it; resume the monitor.
  87. *
  88. * Without this, the monitor would remain suspended forever
  89. * when we get here while the monitor is suspended. An
  90. * unfortunately timed CHR_EVENT_CLOSED can do the trick.
  91. */
  92. monitor_resume(&mon->common);
  93. }
  94. qemu_mutex_unlock(&mon->qmp_queue_lock);
  95. }
  96. void qmp_send_response(MonitorQMP *mon, const QDict *rsp)
  97. {
  98. const QObject *data = QOBJECT(rsp);
  99. QString *json;
  100. json = mon->pretty ? qobject_to_json_pretty(data) : qobject_to_json(data);
  101. assert(json != NULL);
  102. qstring_append_chr(json, '\n');
  103. monitor_puts(&mon->common, qstring_get_str(json));
  104. qobject_unref(json);
  105. }
  106. /*
  107. * Emit QMP response @rsp to @mon.
  108. * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
  109. * Nothing is emitted then.
  110. */
  111. static void monitor_qmp_respond(MonitorQMP *mon, QDict *rsp)
  112. {
  113. if (rsp) {
  114. qmp_send_response(mon, rsp);
  115. }
  116. }
  117. static void monitor_qmp_dispatch(MonitorQMP *mon, QObject *req)
  118. {
  119. Monitor *old_mon;
  120. QDict *rsp;
  121. QDict *error;
  122. old_mon = cur_mon;
  123. cur_mon = &mon->common;
  124. rsp = qmp_dispatch(mon->commands, req, qmp_oob_enabled(mon));
  125. cur_mon = old_mon;
  126. if (mon->commands == &qmp_cap_negotiation_commands) {
  127. error = qdict_get_qdict(rsp, "error");
  128. if (error
  129. && !g_strcmp0(qdict_get_try_str(error, "class"),
  130. QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
  131. /* Provide a more useful error message */
  132. qdict_del(error, "desc");
  133. qdict_put_str(error, "desc", "Expecting capabilities negotiation"
  134. " with 'qmp_capabilities'");
  135. }
  136. }
  137. monitor_qmp_respond(mon, rsp);
  138. qobject_unref(rsp);
  139. }
  140. /*
  141. * Pop a QMP request from a monitor request queue.
  142. * Return the request, or NULL all request queues are empty.
  143. * We are using round-robin fashion to pop the request, to avoid
  144. * processing commands only on a very busy monitor. To achieve that,
  145. * when we process one request on a specific monitor, we put that
  146. * monitor to the end of mon_list queue.
  147. *
  148. * Note: if the function returned with non-NULL, then the caller will
  149. * be with qmp_mon->qmp_queue_lock held, and the caller is responsible
  150. * to release it.
  151. */
  152. static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
  153. {
  154. QMPRequest *req_obj = NULL;
  155. Monitor *mon;
  156. MonitorQMP *qmp_mon;
  157. qemu_mutex_lock(&monitor_lock);
  158. QTAILQ_FOREACH(mon, &mon_list, entry) {
  159. if (!monitor_is_qmp(mon)) {
  160. continue;
  161. }
  162. qmp_mon = container_of(mon, MonitorQMP, common);
  163. qemu_mutex_lock(&qmp_mon->qmp_queue_lock);
  164. req_obj = g_queue_pop_head(qmp_mon->qmp_requests);
  165. if (req_obj) {
  166. /* With the lock of corresponding queue held */
  167. break;
  168. }
  169. qemu_mutex_unlock(&qmp_mon->qmp_queue_lock);
  170. }
  171. if (req_obj) {
  172. /*
  173. * We found one request on the monitor. Degrade this monitor's
  174. * priority to lowest by re-inserting it to end of queue.
  175. */
  176. QTAILQ_REMOVE(&mon_list, mon, entry);
  177. QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
  178. }
  179. qemu_mutex_unlock(&monitor_lock);
  180. return req_obj;
  181. }
  182. void monitor_qmp_bh_dispatcher(void *data)
  183. {
  184. QMPRequest *req_obj = monitor_qmp_requests_pop_any_with_lock();
  185. QDict *rsp;
  186. bool need_resume;
  187. MonitorQMP *mon;
  188. if (!req_obj) {
  189. return;
  190. }
  191. mon = req_obj->mon;
  192. /* qmp_oob_enabled() might change after "qmp_capabilities" */
  193. need_resume = !qmp_oob_enabled(mon) ||
  194. mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1;
  195. qemu_mutex_unlock(&mon->qmp_queue_lock);
  196. if (req_obj->req) {
  197. QDict *qdict = qobject_to(QDict, req_obj->req);
  198. QObject *id = qdict ? qdict_get(qdict, "id") : NULL;
  199. trace_monitor_qmp_cmd_in_band(qobject_get_try_str(id) ?: "");
  200. monitor_qmp_dispatch(mon, req_obj->req);
  201. } else {
  202. assert(req_obj->err);
  203. rsp = qmp_error_response(req_obj->err);
  204. req_obj->err = NULL;
  205. monitor_qmp_respond(mon, rsp);
  206. qobject_unref(rsp);
  207. }
  208. if (need_resume) {
  209. /* Pairs with the monitor_suspend() in handle_qmp_command() */
  210. monitor_resume(&mon->common);
  211. }
  212. qmp_request_free(req_obj);
  213. /* Reschedule instead of looping so the main loop stays responsive */
  214. qemu_bh_schedule(qmp_dispatcher_bh);
  215. }
  216. static void handle_qmp_command(void *opaque, QObject *req, Error *err)
  217. {
  218. MonitorQMP *mon = opaque;
  219. QObject *id = NULL;
  220. QDict *qdict;
  221. QMPRequest *req_obj;
  222. assert(!req != !err);
  223. qdict = qobject_to(QDict, req);
  224. if (qdict) {
  225. id = qdict_get(qdict, "id");
  226. } /* else will fail qmp_dispatch() */
  227. if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
  228. QString *req_json = qobject_to_json(req);
  229. trace_handle_qmp_command(mon, qstring_get_str(req_json));
  230. qobject_unref(req_json);
  231. }
  232. if (qdict && qmp_is_oob(qdict)) {
  233. /* OOB commands are executed immediately */
  234. trace_monitor_qmp_cmd_out_of_band(qobject_get_try_str(id) ?: "");
  235. monitor_qmp_dispatch(mon, req);
  236. qobject_unref(req);
  237. return;
  238. }
  239. req_obj = g_new0(QMPRequest, 1);
  240. req_obj->mon = mon;
  241. req_obj->req = req;
  242. req_obj->err = err;
  243. /* Protect qmp_requests and fetching its length. */
  244. qemu_mutex_lock(&mon->qmp_queue_lock);
  245. /*
  246. * Suspend the monitor when we can't queue more requests after
  247. * this one. Dequeuing in monitor_qmp_bh_dispatcher() or
  248. * monitor_qmp_cleanup_queue_and_resume() will resume it.
  249. * Note that when OOB is disabled, we queue at most one command,
  250. * for backward compatibility.
  251. */
  252. if (!qmp_oob_enabled(mon) ||
  253. mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
  254. monitor_suspend(&mon->common);
  255. }
  256. /*
  257. * Put the request to the end of queue so that requests will be
  258. * handled in time order. Ownership for req_obj, req,
  259. * etc. will be delivered to the handler side.
  260. */
  261. assert(mon->qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
  262. g_queue_push_tail(mon->qmp_requests, req_obj);
  263. qemu_mutex_unlock(&mon->qmp_queue_lock);
  264. /* Kick the dispatcher routine */
  265. qemu_bh_schedule(qmp_dispatcher_bh);
  266. }
  267. static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
  268. {
  269. MonitorQMP *mon = opaque;
  270. json_message_parser_feed(&mon->parser, (const char *) buf, size);
  271. }
  272. static QDict *qmp_greeting(MonitorQMP *mon)
  273. {
  274. QList *cap_list = qlist_new();
  275. QObject *ver = NULL;
  276. QDict *args;
  277. QMPCapability cap;
  278. args = qdict_new();
  279. qmp_marshal_query_version(args, &ver, NULL);
  280. qobject_unref(args);
  281. for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
  282. if (mon->capab_offered[cap]) {
  283. qlist_append_str(cap_list, QMPCapability_str(cap));
  284. }
  285. }
  286. return qdict_from_jsonf_nofail(
  287. "{'QMP': {'version': %p, 'capabilities': %p}}",
  288. ver, cap_list);
  289. }
  290. static void monitor_qmp_event(void *opaque, QEMUChrEvent event)
  291. {
  292. QDict *data;
  293. MonitorQMP *mon = opaque;
  294. switch (event) {
  295. case CHR_EVENT_OPENED:
  296. mon->commands = &qmp_cap_negotiation_commands;
  297. monitor_qmp_caps_reset(mon);
  298. data = qmp_greeting(mon);
  299. qmp_send_response(mon, data);
  300. qobject_unref(data);
  301. mon_refcount++;
  302. break;
  303. case CHR_EVENT_CLOSED:
  304. /*
  305. * Note: this is only useful when the output of the chardev
  306. * backend is still open. For example, when the backend is
  307. * stdio, it's possible that stdout is still open when stdin
  308. * is closed.
  309. */
  310. monitor_qmp_cleanup_queue_and_resume(mon);
  311. json_message_parser_destroy(&mon->parser);
  312. json_message_parser_init(&mon->parser, handle_qmp_command,
  313. mon, NULL);
  314. mon_refcount--;
  315. monitor_fdsets_cleanup();
  316. break;
  317. case CHR_EVENT_BREAK:
  318. case CHR_EVENT_MUX_IN:
  319. case CHR_EVENT_MUX_OUT:
  320. /* Ignore */
  321. break;
  322. }
  323. }
  324. void monitor_data_destroy_qmp(MonitorQMP *mon)
  325. {
  326. json_message_parser_destroy(&mon->parser);
  327. qemu_mutex_destroy(&mon->qmp_queue_lock);
  328. monitor_qmp_cleanup_req_queue_locked(mon);
  329. g_queue_free(mon->qmp_requests);
  330. }
  331. static void monitor_qmp_setup_handlers_bh(void *opaque)
  332. {
  333. MonitorQMP *mon = opaque;
  334. GMainContext *context;
  335. assert(mon->common.use_io_thread);
  336. context = iothread_get_g_main_context(mon_iothread);
  337. assert(context);
  338. qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
  339. monitor_qmp_read, monitor_qmp_event,
  340. NULL, &mon->common, context, true);
  341. monitor_list_append(&mon->common);
  342. }
  343. void monitor_init_qmp(Chardev *chr, bool pretty, Error **errp)
  344. {
  345. MonitorQMP *mon = g_new0(MonitorQMP, 1);
  346. if (!qemu_chr_fe_init(&mon->common.chr, chr, errp)) {
  347. g_free(mon);
  348. return;
  349. }
  350. qemu_chr_fe_set_echo(&mon->common.chr, true);
  351. /* Note: we run QMP monitor in I/O thread when @chr supports that */
  352. monitor_data_init(&mon->common, true, false,
  353. qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
  354. mon->pretty = pretty;
  355. qemu_mutex_init(&mon->qmp_queue_lock);
  356. mon->qmp_requests = g_queue_new();
  357. json_message_parser_init(&mon->parser, handle_qmp_command, mon, NULL);
  358. if (mon->common.use_io_thread) {
  359. /*
  360. * Make sure the old iowatch is gone. It's possible when
  361. * e.g. the chardev is in client mode, with wait=on.
  362. */
  363. remove_fd_in_watch(chr);
  364. /*
  365. * We can't call qemu_chr_fe_set_handlers() directly here
  366. * since chardev might be running in the monitor I/O
  367. * thread. Schedule a bottom half.
  368. */
  369. aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
  370. monitor_qmp_setup_handlers_bh, mon);
  371. /* The bottom half will add @mon to @mon_list */
  372. } else {
  373. qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
  374. monitor_qmp_read, monitor_qmp_event,
  375. NULL, &mon->common, NULL, true);
  376. monitor_list_append(&mon->common);
  377. }
  378. }