2
0

qmp.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. /*
  118. * Runs outside of coroutine context for OOB commands, but in
  119. * coroutine context for everything else.
  120. */
  121. static void monitor_qmp_dispatch(MonitorQMP *mon, QObject *req)
  122. {
  123. QDict *rsp;
  124. QDict *error;
  125. rsp = qmp_dispatch(mon->commands, req, qmp_oob_enabled(mon),
  126. &mon->common);
  127. if (mon->commands == &qmp_cap_negotiation_commands) {
  128. error = qdict_get_qdict(rsp, "error");
  129. if (error
  130. && !g_strcmp0(qdict_get_try_str(error, "class"),
  131. QapiErrorClass_str(ERROR_CLASS_COMMAND_NOT_FOUND))) {
  132. /* Provide a more useful error message */
  133. qdict_del(error, "desc");
  134. qdict_put_str(error, "desc", "Expecting capabilities negotiation"
  135. " with 'qmp_capabilities'");
  136. }
  137. }
  138. monitor_qmp_respond(mon, rsp);
  139. qobject_unref(rsp);
  140. }
  141. /*
  142. * Pop a QMP request from a monitor request queue.
  143. * Return the request, or NULL all request queues are empty.
  144. * We are using round-robin fashion to pop the request, to avoid
  145. * processing commands only on a very busy monitor. To achieve that,
  146. * when we process one request on a specific monitor, we put that
  147. * monitor to the end of mon_list queue.
  148. *
  149. * Note: if the function returned with non-NULL, then the caller will
  150. * be with qmp_mon->qmp_queue_lock held, and the caller is responsible
  151. * to release it.
  152. */
  153. static QMPRequest *monitor_qmp_requests_pop_any_with_lock(void)
  154. {
  155. QMPRequest *req_obj = NULL;
  156. Monitor *mon;
  157. MonitorQMP *qmp_mon;
  158. qemu_mutex_lock(&monitor_lock);
  159. QTAILQ_FOREACH(mon, &mon_list, entry) {
  160. if (!monitor_is_qmp(mon)) {
  161. continue;
  162. }
  163. qmp_mon = container_of(mon, MonitorQMP, common);
  164. qemu_mutex_lock(&qmp_mon->qmp_queue_lock);
  165. req_obj = g_queue_pop_head(qmp_mon->qmp_requests);
  166. if (req_obj) {
  167. /* With the lock of corresponding queue held */
  168. break;
  169. }
  170. qemu_mutex_unlock(&qmp_mon->qmp_queue_lock);
  171. }
  172. if (req_obj) {
  173. /*
  174. * We found one request on the monitor. Degrade this monitor's
  175. * priority to lowest by re-inserting it to end of queue.
  176. */
  177. QTAILQ_REMOVE(&mon_list, mon, entry);
  178. QTAILQ_INSERT_TAIL(&mon_list, mon, entry);
  179. }
  180. qemu_mutex_unlock(&monitor_lock);
  181. return req_obj;
  182. }
  183. void coroutine_fn monitor_qmp_dispatcher_co(void *data)
  184. {
  185. QMPRequest *req_obj = NULL;
  186. QDict *rsp;
  187. bool need_resume;
  188. MonitorQMP *mon;
  189. while (true) {
  190. assert(qatomic_mb_read(&qmp_dispatcher_co_busy) == true);
  191. /*
  192. * Mark the dispatcher as not busy already here so that we
  193. * don't miss any new requests coming in the middle of our
  194. * processing.
  195. */
  196. qatomic_mb_set(&qmp_dispatcher_co_busy, false);
  197. while (!(req_obj = monitor_qmp_requests_pop_any_with_lock())) {
  198. /*
  199. * No more requests to process. Wait to be reentered from
  200. * handle_qmp_command() when it pushes more requests, or
  201. * from monitor_cleanup() when it requests shutdown.
  202. */
  203. if (!qmp_dispatcher_co_shutdown) {
  204. qemu_coroutine_yield();
  205. /*
  206. * busy must be set to true again by whoever
  207. * rescheduled us to avoid double scheduling
  208. */
  209. assert(qatomic_xchg(&qmp_dispatcher_co_busy, false) == true);
  210. }
  211. /*
  212. * qmp_dispatcher_co_shutdown may have changed if we
  213. * yielded and were reentered from monitor_cleanup()
  214. */
  215. if (qmp_dispatcher_co_shutdown) {
  216. return;
  217. }
  218. }
  219. if (qatomic_xchg(&qmp_dispatcher_co_busy, true) == true) {
  220. /*
  221. * Someone rescheduled us (probably because a new requests
  222. * came in), but we didn't actually yield. Do that now,
  223. * only to be immediately reentered and removed from the
  224. * list of scheduled coroutines.
  225. */
  226. qemu_coroutine_yield();
  227. }
  228. /*
  229. * Move the coroutine from iohandler_ctx to qemu_aio_context for
  230. * executing the command handler so that it can make progress if it
  231. * involves an AIO_WAIT_WHILE().
  232. */
  233. aio_co_schedule(qemu_get_aio_context(), qmp_dispatcher_co);
  234. qemu_coroutine_yield();
  235. mon = req_obj->mon;
  236. /* qmp_oob_enabled() might change after "qmp_capabilities" */
  237. need_resume = !qmp_oob_enabled(mon) ||
  238. mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1;
  239. qemu_mutex_unlock(&mon->qmp_queue_lock);
  240. if (req_obj->req) {
  241. QDict *qdict = qobject_to(QDict, req_obj->req);
  242. QObject *id = qdict ? qdict_get(qdict, "id") : NULL;
  243. trace_monitor_qmp_cmd_in_band(qobject_get_try_str(id) ?: "");
  244. monitor_qmp_dispatch(mon, req_obj->req);
  245. } else {
  246. assert(req_obj->err);
  247. rsp = qmp_error_response(req_obj->err);
  248. req_obj->err = NULL;
  249. monitor_qmp_respond(mon, rsp);
  250. qobject_unref(rsp);
  251. }
  252. if (need_resume) {
  253. /* Pairs with the monitor_suspend() in handle_qmp_command() */
  254. monitor_resume(&mon->common);
  255. }
  256. qmp_request_free(req_obj);
  257. /*
  258. * Yield and reschedule so the main loop stays responsive.
  259. *
  260. * Move back to iohandler_ctx so that nested event loops for
  261. * qemu_aio_context don't start new monitor commands.
  262. */
  263. aio_co_schedule(iohandler_get_aio_context(), qmp_dispatcher_co);
  264. qemu_coroutine_yield();
  265. }
  266. }
  267. static void handle_qmp_command(void *opaque, QObject *req, Error *err)
  268. {
  269. MonitorQMP *mon = opaque;
  270. QObject *id = NULL;
  271. QDict *qdict;
  272. QMPRequest *req_obj;
  273. assert(!req != !err);
  274. qdict = qobject_to(QDict, req);
  275. if (qdict) {
  276. id = qdict_get(qdict, "id");
  277. } /* else will fail qmp_dispatch() */
  278. if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
  279. QString *req_json = qobject_to_json(req);
  280. trace_handle_qmp_command(mon, qstring_get_str(req_json));
  281. qobject_unref(req_json);
  282. }
  283. if (qdict && qmp_is_oob(qdict)) {
  284. /* OOB commands are executed immediately */
  285. trace_monitor_qmp_cmd_out_of_band(qobject_get_try_str(id) ?: "");
  286. monitor_qmp_dispatch(mon, req);
  287. qobject_unref(req);
  288. return;
  289. }
  290. req_obj = g_new0(QMPRequest, 1);
  291. req_obj->mon = mon;
  292. req_obj->req = req;
  293. req_obj->err = err;
  294. /* Protect qmp_requests and fetching its length. */
  295. qemu_mutex_lock(&mon->qmp_queue_lock);
  296. /*
  297. * Suspend the monitor when we can't queue more requests after
  298. * this one. Dequeuing in monitor_qmp_bh_dispatcher() or
  299. * monitor_qmp_cleanup_queue_and_resume() will resume it.
  300. * Note that when OOB is disabled, we queue at most one command,
  301. * for backward compatibility.
  302. */
  303. if (!qmp_oob_enabled(mon) ||
  304. mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
  305. monitor_suspend(&mon->common);
  306. }
  307. /*
  308. * Put the request to the end of queue so that requests will be
  309. * handled in time order. Ownership for req_obj, req,
  310. * etc. will be delivered to the handler side.
  311. */
  312. assert(mon->qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
  313. g_queue_push_tail(mon->qmp_requests, req_obj);
  314. qemu_mutex_unlock(&mon->qmp_queue_lock);
  315. /* Kick the dispatcher routine */
  316. if (!qatomic_xchg(&qmp_dispatcher_co_busy, true)) {
  317. aio_co_wake(qmp_dispatcher_co);
  318. }
  319. }
  320. static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
  321. {
  322. MonitorQMP *mon = opaque;
  323. json_message_parser_feed(&mon->parser, (const char *) buf, size);
  324. }
  325. static QDict *qmp_greeting(MonitorQMP *mon)
  326. {
  327. QList *cap_list = qlist_new();
  328. QObject *ver = NULL;
  329. QDict *args;
  330. QMPCapability cap;
  331. args = qdict_new();
  332. qmp_marshal_query_version(args, &ver, NULL);
  333. qobject_unref(args);
  334. for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
  335. if (mon->capab_offered[cap]) {
  336. qlist_append_str(cap_list, QMPCapability_str(cap));
  337. }
  338. }
  339. return qdict_from_jsonf_nofail(
  340. "{'QMP': {'version': %p, 'capabilities': %p}}",
  341. ver, cap_list);
  342. }
  343. static void monitor_qmp_event(void *opaque, QEMUChrEvent event)
  344. {
  345. QDict *data;
  346. MonitorQMP *mon = opaque;
  347. switch (event) {
  348. case CHR_EVENT_OPENED:
  349. mon->commands = &qmp_cap_negotiation_commands;
  350. monitor_qmp_caps_reset(mon);
  351. data = qmp_greeting(mon);
  352. qmp_send_response(mon, data);
  353. qobject_unref(data);
  354. mon_refcount++;
  355. break;
  356. case CHR_EVENT_CLOSED:
  357. /*
  358. * Note: this is only useful when the output of the chardev
  359. * backend is still open. For example, when the backend is
  360. * stdio, it's possible that stdout is still open when stdin
  361. * is closed.
  362. */
  363. monitor_qmp_cleanup_queue_and_resume(mon);
  364. json_message_parser_destroy(&mon->parser);
  365. json_message_parser_init(&mon->parser, handle_qmp_command,
  366. mon, NULL);
  367. mon_refcount--;
  368. monitor_fdsets_cleanup();
  369. break;
  370. case CHR_EVENT_BREAK:
  371. case CHR_EVENT_MUX_IN:
  372. case CHR_EVENT_MUX_OUT:
  373. /* Ignore */
  374. break;
  375. }
  376. }
  377. void monitor_data_destroy_qmp(MonitorQMP *mon)
  378. {
  379. json_message_parser_destroy(&mon->parser);
  380. qemu_mutex_destroy(&mon->qmp_queue_lock);
  381. monitor_qmp_cleanup_req_queue_locked(mon);
  382. g_queue_free(mon->qmp_requests);
  383. }
  384. static void monitor_qmp_setup_handlers_bh(void *opaque)
  385. {
  386. MonitorQMP *mon = opaque;
  387. GMainContext *context;
  388. assert(mon->common.use_io_thread);
  389. context = iothread_get_g_main_context(mon_iothread);
  390. assert(context);
  391. qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
  392. monitor_qmp_read, monitor_qmp_event,
  393. NULL, &mon->common, context, true);
  394. monitor_list_append(&mon->common);
  395. }
  396. void monitor_init_qmp(Chardev *chr, bool pretty, Error **errp)
  397. {
  398. MonitorQMP *mon = g_new0(MonitorQMP, 1);
  399. if (!qemu_chr_fe_init(&mon->common.chr, chr, errp)) {
  400. g_free(mon);
  401. return;
  402. }
  403. qemu_chr_fe_set_echo(&mon->common.chr, true);
  404. /* Note: we run QMP monitor in I/O thread when @chr supports that */
  405. monitor_data_init(&mon->common, true, false,
  406. qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
  407. mon->pretty = pretty;
  408. qemu_mutex_init(&mon->qmp_queue_lock);
  409. mon->qmp_requests = g_queue_new();
  410. json_message_parser_init(&mon->parser, handle_qmp_command, mon, NULL);
  411. if (mon->common.use_io_thread) {
  412. /*
  413. * Make sure the old iowatch is gone. It's possible when
  414. * e.g. the chardev is in client mode, with wait=on.
  415. */
  416. remove_fd_in_watch(chr);
  417. /*
  418. * We can't call qemu_chr_fe_set_handlers() directly here
  419. * since chardev might be running in the monitor I/O
  420. * thread. Schedule a bottom half.
  421. */
  422. aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
  423. monitor_qmp_setup_handlers_bh, mon);
  424. /* The bottom half will add @mon to @mon_list */
  425. } else {
  426. qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
  427. monitor_qmp_read, monitor_qmp_event,
  428. NULL, &mon->common, NULL, true);
  429. monitor_list_append(&mon->common);
  430. }
  431. }