qmp.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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 "trace.h"
  33. struct QMPRequest {
  34. /* Owner of the request */
  35. MonitorQMP *mon;
  36. /*
  37. * Request object to be handled or Error to be reported
  38. * (exactly one of them is non-null)
  39. */
  40. QObject *req;
  41. Error *err;
  42. };
  43. typedef struct QMPRequest QMPRequest;
  44. QmpCommandList qmp_commands, qmp_cap_negotiation_commands;
  45. static bool qmp_oob_enabled(MonitorQMP *mon)
  46. {
  47. return mon->capab[QMP_CAPABILITY_OOB];
  48. }
  49. static void monitor_qmp_caps_reset(MonitorQMP *mon)
  50. {
  51. memset(mon->capab_offered, 0, sizeof(mon->capab_offered));
  52. memset(mon->capab, 0, sizeof(mon->capab));
  53. mon->capab_offered[QMP_CAPABILITY_OOB] = mon->common.use_io_thread;
  54. }
  55. static void qmp_request_free(QMPRequest *req)
  56. {
  57. qobject_unref(req->req);
  58. error_free(req->err);
  59. g_free(req);
  60. }
  61. /* Caller must hold mon->qmp.qmp_queue_lock */
  62. static void monitor_qmp_cleanup_req_queue_locked(MonitorQMP *mon)
  63. {
  64. while (!g_queue_is_empty(mon->qmp_requests)) {
  65. qmp_request_free(g_queue_pop_head(mon->qmp_requests));
  66. }
  67. }
  68. static void monitor_qmp_cleanup_queue_and_resume(MonitorQMP *mon)
  69. {
  70. QEMU_LOCK_GUARD(&mon->qmp_queue_lock);
  71. /*
  72. * Same condition as in monitor_qmp_dispatcher_co(), but before
  73. * removing an element from the queue (hence no `- 1`).
  74. * Also, the queue should not be empty either, otherwise the
  75. * monitor hasn't been suspended yet (or was already resumed).
  76. */
  77. bool need_resume = (!qmp_oob_enabled(mon) ||
  78. mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX)
  79. && !g_queue_is_empty(mon->qmp_requests);
  80. monitor_qmp_cleanup_req_queue_locked(mon);
  81. if (need_resume) {
  82. /*
  83. * handle_qmp_command() suspended the monitor because the
  84. * request queue filled up, to be resumed when the queue has
  85. * space again. We just emptied it; resume the monitor.
  86. *
  87. * Without this, the monitor would remain suspended forever
  88. * when we get here while the monitor is suspended. An
  89. * unfortunately timed CHR_EVENT_CLOSED can do the trick.
  90. */
  91. monitor_resume(&mon->common);
  92. }
  93. }
  94. void qmp_send_response(MonitorQMP *mon, const QDict *rsp)
  95. {
  96. const QObject *data = QOBJECT(rsp);
  97. GString *json;
  98. json = qobject_to_json_pretty(data, mon->pretty);
  99. assert(json != NULL);
  100. trace_monitor_qmp_respond(mon, json->str);
  101. g_string_append_c(json, '\n');
  102. monitor_puts(&mon->common, json->str);
  103. g_string_free(json, true);
  104. }
  105. /*
  106. * Emit QMP response @rsp to @mon.
  107. * Null @rsp can only happen for commands with QCO_NO_SUCCESS_RESP.
  108. * Nothing is emitted then.
  109. */
  110. static void monitor_qmp_respond(MonitorQMP *mon, QDict *rsp)
  111. {
  112. if (rsp) {
  113. qmp_send_response(mon, rsp);
  114. }
  115. }
  116. /*
  117. * Runs outside of coroutine context for OOB commands, but in
  118. * coroutine context for everything else.
  119. */
  120. static void monitor_qmp_dispatch(MonitorQMP *mon, QObject *req)
  121. {
  122. QDict *rsp;
  123. QDict *error;
  124. rsp = qmp_dispatch(mon->commands, req, qmp_oob_enabled(mon),
  125. &mon->common);
  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_LOCK_GUARD(&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. return req_obj;
  180. }
  181. void coroutine_fn monitor_qmp_dispatcher_co(void *data)
  182. {
  183. QMPRequest *req_obj = NULL;
  184. QDict *rsp;
  185. bool oob_enabled;
  186. MonitorQMP *mon;
  187. while (true) {
  188. assert(qatomic_mb_read(&qmp_dispatcher_co_busy) == true);
  189. /*
  190. * Mark the dispatcher as not busy already here so that we
  191. * don't miss any new requests coming in the middle of our
  192. * processing.
  193. */
  194. qatomic_mb_set(&qmp_dispatcher_co_busy, false);
  195. /* On shutdown, don't take any more requests from the queue */
  196. if (qmp_dispatcher_co_shutdown) {
  197. return;
  198. }
  199. while (!(req_obj = monitor_qmp_requests_pop_any_with_lock())) {
  200. /*
  201. * No more requests to process. Wait to be reentered from
  202. * handle_qmp_command() when it pushes more requests, or
  203. * from monitor_cleanup() when it requests shutdown.
  204. */
  205. if (!qmp_dispatcher_co_shutdown) {
  206. qemu_coroutine_yield();
  207. /*
  208. * busy must be set to true again by whoever
  209. * rescheduled us to avoid double scheduling
  210. */
  211. assert(qatomic_xchg(&qmp_dispatcher_co_busy, false) == true);
  212. }
  213. /*
  214. * qmp_dispatcher_co_shutdown may have changed if we
  215. * yielded and were reentered from monitor_cleanup()
  216. */
  217. if (qmp_dispatcher_co_shutdown) {
  218. return;
  219. }
  220. }
  221. trace_monitor_qmp_in_band_dequeue(req_obj,
  222. req_obj->mon->qmp_requests->length);
  223. /*
  224. * @req_obj has a request, we hold req_obj->mon->qmp_queue_lock
  225. */
  226. mon = req_obj->mon;
  227. /*
  228. * We need to resume the monitor if handle_qmp_command()
  229. * suspended it. Two cases:
  230. * 1. OOB enabled: mon->qmp_requests has no more space
  231. * Resume right away, so that OOB commands can get executed while
  232. * this request is being processed.
  233. * 2. OOB disabled: always
  234. * Resume only after we're done processing the request,
  235. * We need to save qmp_oob_enabled() for later, because
  236. * qmp_qmp_capabilities() can change it.
  237. */
  238. oob_enabled = qmp_oob_enabled(mon);
  239. if (oob_enabled
  240. && mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
  241. monitor_resume(&mon->common);
  242. }
  243. /*
  244. * Drop the queue mutex now, before yielding, otherwise we might
  245. * deadlock if the main thread tries to lock it.
  246. */
  247. qemu_mutex_unlock(&mon->qmp_queue_lock);
  248. if (qatomic_xchg(&qmp_dispatcher_co_busy, true) == true) {
  249. /*
  250. * Someone rescheduled us (probably because a new requests
  251. * came in), but we didn't actually yield. Do that now,
  252. * only to be immediately reentered and removed from the
  253. * list of scheduled coroutines.
  254. */
  255. qemu_coroutine_yield();
  256. }
  257. /*
  258. * Move the coroutine from iohandler_ctx to qemu_aio_context for
  259. * executing the command handler so that it can make progress if it
  260. * involves an AIO_WAIT_WHILE().
  261. */
  262. aio_co_schedule(qemu_get_aio_context(), qmp_dispatcher_co);
  263. qemu_coroutine_yield();
  264. /* Process request */
  265. if (req_obj->req) {
  266. if (trace_event_get_state(TRACE_MONITOR_QMP_CMD_IN_BAND)) {
  267. QDict *qdict = qobject_to(QDict, req_obj->req);
  268. QObject *id = qdict ? qdict_get(qdict, "id") : NULL;
  269. GString *id_json;
  270. id_json = id ? qobject_to_json(id) : g_string_new(NULL);
  271. trace_monitor_qmp_cmd_in_band(id_json->str);
  272. g_string_free(id_json, true);
  273. }
  274. monitor_qmp_dispatch(mon, req_obj->req);
  275. } else {
  276. assert(req_obj->err);
  277. trace_monitor_qmp_err_in_band(error_get_pretty(req_obj->err));
  278. rsp = qmp_error_response(req_obj->err);
  279. req_obj->err = NULL;
  280. monitor_qmp_respond(mon, rsp);
  281. qobject_unref(rsp);
  282. }
  283. if (!oob_enabled) {
  284. monitor_resume(&mon->common);
  285. }
  286. qmp_request_free(req_obj);
  287. /*
  288. * Yield and reschedule so the main loop stays responsive.
  289. *
  290. * Move back to iohandler_ctx so that nested event loops for
  291. * qemu_aio_context don't start new monitor commands.
  292. */
  293. aio_co_schedule(iohandler_get_aio_context(), qmp_dispatcher_co);
  294. qemu_coroutine_yield();
  295. }
  296. }
  297. static void handle_qmp_command(void *opaque, QObject *req, Error *err)
  298. {
  299. MonitorQMP *mon = opaque;
  300. QDict *qdict = qobject_to(QDict, req);
  301. QMPRequest *req_obj;
  302. assert(!req != !err);
  303. if (req && trace_event_get_state_backends(TRACE_HANDLE_QMP_COMMAND)) {
  304. GString *req_json = qobject_to_json(req);
  305. trace_handle_qmp_command(mon, req_json->str);
  306. g_string_free(req_json, true);
  307. }
  308. if (qdict && qmp_is_oob(qdict)) {
  309. /* OOB commands are executed immediately */
  310. if (trace_event_get_state(TRACE_MONITOR_QMP_CMD_OUT_OF_BAND)) {
  311. QObject *id = qdict_get(qdict, "id");
  312. GString *id_json;
  313. id_json = id ? qobject_to_json(id) : g_string_new(NULL);
  314. trace_monitor_qmp_cmd_out_of_band(id_json->str);
  315. g_string_free(id_json, true);
  316. }
  317. monitor_qmp_dispatch(mon, req);
  318. qobject_unref(req);
  319. return;
  320. }
  321. req_obj = g_new0(QMPRequest, 1);
  322. req_obj->mon = mon;
  323. req_obj->req = req;
  324. req_obj->err = err;
  325. /* Protect qmp_requests and fetching its length. */
  326. WITH_QEMU_LOCK_GUARD(&mon->qmp_queue_lock) {
  327. /*
  328. * Suspend the monitor when we can't queue more requests after
  329. * this one. Dequeuing in monitor_qmp_dispatcher_co() or
  330. * monitor_qmp_cleanup_queue_and_resume() will resume it.
  331. * Note that when OOB is disabled, we queue at most one command,
  332. * for backward compatibility.
  333. */
  334. if (!qmp_oob_enabled(mon) ||
  335. mon->qmp_requests->length == QMP_REQ_QUEUE_LEN_MAX - 1) {
  336. monitor_suspend(&mon->common);
  337. }
  338. /*
  339. * Put the request to the end of queue so that requests will be
  340. * handled in time order. Ownership for req_obj, req,
  341. * etc. will be delivered to the handler side.
  342. */
  343. trace_monitor_qmp_in_band_enqueue(req_obj, mon,
  344. mon->qmp_requests->length);
  345. assert(mon->qmp_requests->length < QMP_REQ_QUEUE_LEN_MAX);
  346. g_queue_push_tail(mon->qmp_requests, req_obj);
  347. }
  348. /* Kick the dispatcher routine */
  349. if (!qatomic_xchg(&qmp_dispatcher_co_busy, true)) {
  350. aio_co_wake(qmp_dispatcher_co);
  351. }
  352. }
  353. static void monitor_qmp_read(void *opaque, const uint8_t *buf, int size)
  354. {
  355. MonitorQMP *mon = opaque;
  356. json_message_parser_feed(&mon->parser, (const char *) buf, size);
  357. }
  358. static QDict *qmp_greeting(MonitorQMP *mon)
  359. {
  360. QList *cap_list = qlist_new();
  361. QObject *ver = NULL;
  362. QDict *args;
  363. QMPCapability cap;
  364. args = qdict_new();
  365. qmp_marshal_query_version(args, &ver, NULL);
  366. qobject_unref(args);
  367. for (cap = 0; cap < QMP_CAPABILITY__MAX; cap++) {
  368. if (mon->capab_offered[cap]) {
  369. qlist_append_str(cap_list, QMPCapability_str(cap));
  370. }
  371. }
  372. return qdict_from_jsonf_nofail(
  373. "{'QMP': {'version': %p, 'capabilities': %p}}",
  374. ver, cap_list);
  375. }
  376. static void monitor_qmp_event(void *opaque, QEMUChrEvent event)
  377. {
  378. QDict *data;
  379. MonitorQMP *mon = opaque;
  380. switch (event) {
  381. case CHR_EVENT_OPENED:
  382. mon->commands = &qmp_cap_negotiation_commands;
  383. monitor_qmp_caps_reset(mon);
  384. data = qmp_greeting(mon);
  385. qmp_send_response(mon, data);
  386. qobject_unref(data);
  387. mon_refcount++;
  388. break;
  389. case CHR_EVENT_CLOSED:
  390. /*
  391. * Note: this is only useful when the output of the chardev
  392. * backend is still open. For example, when the backend is
  393. * stdio, it's possible that stdout is still open when stdin
  394. * is closed.
  395. */
  396. monitor_qmp_cleanup_queue_and_resume(mon);
  397. json_message_parser_destroy(&mon->parser);
  398. json_message_parser_init(&mon->parser, handle_qmp_command,
  399. mon, NULL);
  400. mon_refcount--;
  401. monitor_fdsets_cleanup();
  402. break;
  403. case CHR_EVENT_BREAK:
  404. case CHR_EVENT_MUX_IN:
  405. case CHR_EVENT_MUX_OUT:
  406. /* Ignore */
  407. break;
  408. }
  409. }
  410. void monitor_data_destroy_qmp(MonitorQMP *mon)
  411. {
  412. json_message_parser_destroy(&mon->parser);
  413. qemu_mutex_destroy(&mon->qmp_queue_lock);
  414. monitor_qmp_cleanup_req_queue_locked(mon);
  415. g_queue_free(mon->qmp_requests);
  416. }
  417. static void monitor_qmp_setup_handlers_bh(void *opaque)
  418. {
  419. MonitorQMP *mon = opaque;
  420. GMainContext *context;
  421. assert(mon->common.use_io_thread);
  422. context = iothread_get_g_main_context(mon_iothread);
  423. assert(context);
  424. qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
  425. monitor_qmp_read, monitor_qmp_event,
  426. NULL, &mon->common, context, true);
  427. monitor_list_append(&mon->common);
  428. }
  429. void monitor_init_qmp(Chardev *chr, bool pretty, Error **errp)
  430. {
  431. MonitorQMP *mon = g_new0(MonitorQMP, 1);
  432. if (!qemu_chr_fe_init(&mon->common.chr, chr, errp)) {
  433. g_free(mon);
  434. return;
  435. }
  436. qemu_chr_fe_set_echo(&mon->common.chr, true);
  437. /* Note: we run QMP monitor in I/O thread when @chr supports that */
  438. monitor_data_init(&mon->common, true, false,
  439. qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
  440. mon->pretty = pretty;
  441. qemu_mutex_init(&mon->qmp_queue_lock);
  442. mon->qmp_requests = g_queue_new();
  443. json_message_parser_init(&mon->parser, handle_qmp_command, mon, NULL);
  444. if (mon->common.use_io_thread) {
  445. /*
  446. * Make sure the old iowatch is gone. It's possible when
  447. * e.g. the chardev is in client mode, with wait=on.
  448. */
  449. remove_fd_in_watch(chr);
  450. /*
  451. * We can't call qemu_chr_fe_set_handlers() directly here
  452. * since chardev might be running in the monitor I/O
  453. * thread. Schedule a bottom half.
  454. */
  455. aio_bh_schedule_oneshot(iothread_get_aio_context(mon_iothread),
  456. monitor_qmp_setup_handlers_bh, mon);
  457. /* The bottom half will add @mon to @mon_list */
  458. } else {
  459. qemu_chr_fe_set_handlers(&mon->common.chr, monitor_can_read,
  460. monitor_qmp_read, monitor_qmp_event,
  461. NULL, &mon->common, NULL, true);
  462. monitor_list_append(&mon->common);
  463. }
  464. }