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