]> git.proxmox.com Git - mirror_qemu.git/blob - docs/qapi-code-gen.txt
Merge remote-tracking branch 'remotes/qmp-unstable/queue/qmp' into staging
[mirror_qemu.git] / docs / qapi-code-gen.txt
1 = How to use the QAPI code generator =
2
3 QAPI is a native C API within QEMU which provides management-level
4 functionality to internal/external users. For external
5 users/processes, this interface is made available by a JSON-based
6 QEMU Monitor protocol that is provided by the QMP server.
7
8 To map QMP-defined interfaces to the native C QAPI implementations,
9 a JSON-based schema is used to define types and function
10 signatures, and a set of scripts is used to generate types/signatures,
11 and marshaling/dispatch code. The QEMU Guest Agent also uses these
12 scripts, paired with a separate schema, to generate
13 marshaling/dispatch code for the guest agent server running in the
14 guest.
15
16 This document will describe how the schemas, scripts, and resulting
17 code are used.
18
19
20 == QMP/Guest agent schema ==
21
22 This file defines the types, commands, and events used by QMP. It should
23 fully describe the interface used by QMP.
24
25 This file is designed to be loosely based on JSON although it's technically
26 executable Python. While dictionaries are used, they are parsed as
27 OrderedDicts so that ordering is preserved.
28
29 There are two basic syntaxes used, type definitions and command definitions.
30
31 The first syntax defines a type and is represented by a dictionary. There are
32 three kinds of user-defined types that are supported: complex types,
33 enumeration types and union types.
34
35 Generally speaking, types definitions should always use CamelCase for the type
36 names. Command names should be all lower case with words separated by a hyphen.
37
38
39 === Includes ===
40
41 The QAPI schema definitions can be modularized using the 'include' directive:
42
43 { 'include': 'path/to/file.json'}
44
45 The directive is evaluated recursively, and include paths are relative to the
46 file using the directive. Multiple includes of the same file are safe.
47
48
49 === Complex types ===
50
51 A complex type is a dictionary containing a single key whose value is a
52 dictionary. This corresponds to a struct in C or an Object in JSON. An
53 example of a complex type is:
54
55 { 'type': 'MyType',
56 'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
57
58 The use of '*' as a prefix to the name means the member is optional.
59
60 The default initialization value of an optional argument should not be changed
61 between versions of QEMU unless the new default maintains backward
62 compatibility to the user-visible behavior of the old default.
63
64 With proper documentation, this policy still allows some flexibility; for
65 example, documenting that a default of 0 picks an optimal buffer size allows
66 one release to declare the optimal size at 512 while another release declares
67 the optimal size at 4096 - the user-visible behavior is not the bytes used by
68 the buffer, but the fact that the buffer was optimal size.
69
70 On input structures (only mentioned in the 'data' side of a command), changing
71 from mandatory to optional is safe (older clients will supply the option, and
72 newer clients can benefit from the default); changing from optional to
73 mandatory is backwards incompatible (older clients may be omitting the option,
74 and must continue to work).
75
76 On output structures (only mentioned in the 'returns' side of a command),
77 changing from mandatory to optional is in general unsafe (older clients may be
78 expecting the field, and could crash if it is missing), although it can be done
79 if the only way that the optional argument will be omitted is when it is
80 triggered by the presence of a new input flag to the command that older clients
81 don't know to send. Changing from optional to mandatory is safe.
82
83 A structure that is used in both input and output of various commands
84 must consider the backwards compatibility constraints of both directions
85 of use.
86
87 A complex type definition can specify another complex type as its base.
88 In this case, the fields of the base type are included as top-level fields
89 of the new complex type's dictionary in the QMP wire format. An example
90 definition is:
91
92 { 'type': 'BlockdevOptionsGenericFormat', 'data': { 'file': 'str' } }
93 { 'type': 'BlockdevOptionsGenericCOWFormat',
94 'base': 'BlockdevOptionsGenericFormat',
95 'data': { '*backing': 'str' } }
96
97 An example BlockdevOptionsGenericCOWFormat object on the wire could use
98 both fields like this:
99
100 { "file": "/some/place/my-image",
101 "backing": "/some/place/my-backing-file" }
102
103 === Enumeration types ===
104
105 An enumeration type is a dictionary containing a single key whose value is a
106 list of strings. An example enumeration is:
107
108 { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
109
110 === Union types ===
111
112 Union types are used to let the user choose between several different data
113 types. A union type is defined using a dictionary as explained in the
114 following paragraphs.
115
116
117 A simple union type defines a mapping from discriminator values to data types
118 like in this example:
119
120 { 'type': 'FileOptions', 'data': { 'filename': 'str' } }
121 { 'type': 'Qcow2Options',
122 'data': { 'backing-file': 'str', 'lazy-refcounts': 'bool' } }
123
124 { 'union': 'BlockdevOptions',
125 'data': { 'file': 'FileOptions',
126 'qcow2': 'Qcow2Options' } }
127
128 In the QMP wire format, a simple union is represented by a dictionary that
129 contains the 'type' field as a discriminator, and a 'data' field that is of the
130 specified data type corresponding to the discriminator value:
131
132 { "type": "qcow2", "data" : { "backing-file": "/some/place/my-image",
133 "lazy-refcounts": true } }
134
135
136 A union definition can specify a complex type as its base. In this case, the
137 fields of the complex type are included as top-level fields of the union
138 dictionary in the QMP wire format. An example definition is:
139
140 { 'type': 'BlockdevCommonOptions', 'data': { 'readonly': 'bool' } }
141 { 'union': 'BlockdevOptions',
142 'base': 'BlockdevCommonOptions',
143 'data': { 'raw': 'RawOptions',
144 'qcow2': 'Qcow2Options' } }
145
146 And it looks like this on the wire:
147
148 { "type": "qcow2",
149 "readonly": false,
150 "data" : { "backing-file": "/some/place/my-image",
151 "lazy-refcounts": true } }
152
153
154 Flat union types avoid the nesting on the wire. They are used whenever a
155 specific field of the base type is declared as the discriminator ('type' is
156 then no longer generated). The discriminator must be of enumeration type.
157 The above example can then be modified as follows:
158
159 { 'enum': 'BlockdevDriver', 'data': [ 'raw', 'qcow2' ] }
160 { 'type': 'BlockdevCommonOptions',
161 'data': { 'driver': 'BlockdevDriver', 'readonly': 'bool' } }
162 { 'union': 'BlockdevOptions',
163 'base': 'BlockdevCommonOptions',
164 'discriminator': 'driver',
165 'data': { 'raw': 'RawOptions',
166 'qcow2': 'Qcow2Options' } }
167
168 Resulting in this JSON object:
169
170 { "driver": "qcow2",
171 "readonly": false,
172 "backing-file": "/some/place/my-image",
173 "lazy-refcounts": true }
174
175
176 A special type of unions are anonymous unions. They don't form a dictionary in
177 the wire format but allow the direct use of different types in their place. As
178 they aren't structured, they don't have any explicit discriminator but use
179 the (QObject) data type of their value as an implicit discriminator. This means
180 that they are restricted to using only one discriminator value per QObject
181 type. For example, you cannot have two different complex types in an anonymous
182 union, or two different integer types.
183
184 Anonymous unions are declared using an empty dictionary as their discriminator.
185 The discriminator values never appear on the wire, they are only used in the
186 generated C code. Anonymous unions cannot have a base type.
187
188 { 'union': 'BlockRef',
189 'discriminator': {},
190 'data': { 'definition': 'BlockdevOptions',
191 'reference': 'str' } }
192
193 This example allows using both of the following example objects:
194
195 { "file": "my_existing_block_device_id" }
196 { "file": { "driver": "file",
197 "readonly": false,
198 "filename": "/tmp/mydisk.qcow2" } }
199
200
201 === Commands ===
202
203 Commands are defined by using a list containing three members. The first
204 member is the command name, the second member is a dictionary containing
205 arguments, and the third member is the return type.
206
207 An example command is:
208
209 { 'command': 'my-command',
210 'data': { 'arg1': 'str', '*arg2': 'str' },
211 'returns': 'str' }
212
213 === Events ===
214
215 Events are defined with the keyword 'event'. When 'data' is also specified,
216 additional info will be included in the event. Finally there will be C API
217 generated in qapi-event.h; when called by QEMU code, a message with timestamp
218 will be emitted on the wire. If timestamp is -1, it means failure to retrieve
219 host time.
220
221 An example event is:
222
223 { 'event': 'EVENT_C',
224 'data': { '*a': 'int', 'b': 'str' } }
225
226 Resulting in this JSON object:
227
228 { "event": "EVENT_C",
229 "data": { "b": "test string" },
230 "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
231
232
233 == Code generation ==
234
235 Schemas are fed into 3 scripts to generate all the code/files that, paired
236 with the core QAPI libraries, comprise everything required to take JSON
237 commands read in by a QMP/guest agent server, unmarshal the arguments into
238 the underlying C types, call into the corresponding C function, and map the
239 response back to a QMP/guest agent response to be returned to the user.
240
241 As an example, we'll use the following schema, which describes a single
242 complex user-defined type (which will produce a C struct, along with a list
243 node structure that can be used to chain together a list of such types in
244 case we want to accept/return a list of this type with a command), and a
245 command which takes that type as a parameter and returns the same type:
246
247 $ cat example-schema.json
248 { 'type': 'UserDefOne',
249 'data': { 'integer': 'int', 'string': 'str' } }
250
251 { 'command': 'my-command',
252 'data': {'arg1': 'UserDefOne'},
253 'returns': 'UserDefOne' }
254
255 { 'event': 'MY_EVENT' }
256
257 === scripts/qapi-types.py ===
258
259 Used to generate the C types defined by a schema. The following files are
260 created:
261
262 $(prefix)qapi-types.h - C types corresponding to types defined in
263 the schema you pass in
264 $(prefix)qapi-types.c - Cleanup functions for the above C types
265
266 The $(prefix) is an optional parameter used as a namespace to keep the
267 generated code from one schema/code-generation separated from others so code
268 can be generated/used from multiple schemas without clobbering previously
269 created code.
270
271 Example:
272
273 $ python scripts/qapi-types.py --output-dir="qapi-generated" \
274 --prefix="example-" --input-file=example-schema.json
275 $ cat qapi-generated/example-qapi-types.c
276 [Uninteresting stuff omitted...]
277
278 void qapi_free_UserDefOneList(UserDefOneList *obj)
279 {
280 QapiDeallocVisitor *md;
281 Visitor *v;
282
283 if (!obj) {
284 return;
285 }
286
287 md = qapi_dealloc_visitor_new();
288 v = qapi_dealloc_get_visitor(md);
289 visit_type_UserDefOneList(v, &obj, NULL, NULL);
290 qapi_dealloc_visitor_cleanup(md);
291 }
292
293 void qapi_free_UserDefOne(UserDefOne *obj)
294 {
295 QapiDeallocVisitor *md;
296 Visitor *v;
297
298 if (!obj) {
299 return;
300 }
301
302 md = qapi_dealloc_visitor_new();
303 v = qapi_dealloc_get_visitor(md);
304 visit_type_UserDefOne(v, &obj, NULL, NULL);
305 qapi_dealloc_visitor_cleanup(md);
306 }
307
308 $ cat qapi-generated/example-qapi-types.h
309 [Uninteresting stuff omitted...]
310
311 #ifndef EXAMPLE_QAPI_TYPES_H
312 #define EXAMPLE_QAPI_TYPES_H
313
314 [Builtin types omitted...]
315
316 typedef struct UserDefOne UserDefOne;
317
318 typedef struct UserDefOneList
319 {
320 union {
321 UserDefOne *value;
322 uint64_t padding;
323 };
324 struct UserDefOneList *next;
325 } UserDefOneList;
326
327 [Functions on builtin types omitted...]
328
329 struct UserDefOne
330 {
331 int64_t integer;
332 char *string;
333 };
334
335 void qapi_free_UserDefOneList(UserDefOneList *obj);
336 void qapi_free_UserDefOne(UserDefOne *obj);
337
338 #endif
339
340 === scripts/qapi-visit.py ===
341
342 Used to generate the visitor functions used to walk through and convert
343 a QObject (as provided by QMP) to a native C data structure and
344 vice-versa, as well as the visitor function used to dealloc a complex
345 schema-defined C type.
346
347 The following files are generated:
348
349 $(prefix)qapi-visit.c: visitor function for a particular C type, used
350 to automagically convert QObjects into the
351 corresponding C type and vice-versa, as well
352 as for deallocating memory for an existing C
353 type
354
355 $(prefix)qapi-visit.h: declarations for previously mentioned visitor
356 functions
357
358 Example:
359
360 $ python scripts/qapi-visit.py --output-dir="qapi-generated"
361 --prefix="example-" --input-file=example-schema.json
362 $ cat qapi-generated/example-qapi-visit.c
363 [Uninteresting stuff omitted...]
364
365 static void visit_type_UserDefOne_fields(Visitor *m, UserDefOne **obj, Error **errp)
366 {
367 Error *err = NULL;
368 visit_type_int(m, &(*obj)->integer, "integer", &err);
369 if (err) {
370 goto out;
371 }
372 visit_type_str(m, &(*obj)->string, "string", &err);
373 if (err) {
374 goto out;
375 }
376
377 out:
378 error_propagate(errp, err);
379 }
380
381 void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp)
382 {
383 Error *err = NULL;
384
385 visit_start_struct(m, (void **)obj, "UserDefOne", name, sizeof(UserDefOne), &err);
386 if (!err) {
387 if (*obj) {
388 visit_type_UserDefOne_fields(m, obj, errp);
389 }
390 visit_end_struct(m, &err);
391 }
392 error_propagate(errp, err);
393 }
394
395 void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp)
396 {
397 Error *err = NULL;
398 GenericList *i, **prev;
399
400 visit_start_list(m, name, &err);
401 if (err) {
402 goto out;
403 }
404
405 for (prev = (GenericList **)obj;
406 !err && (i = visit_next_list(m, prev, &err)) != NULL;
407 prev = &i) {
408 UserDefOneList *native_i = (UserDefOneList *)i;
409 visit_type_UserDefOne(m, &native_i->value, NULL, &err);
410 }
411
412 error_propagate(errp, err);
413 err = NULL;
414 visit_end_list(m, &err);
415 out:
416 error_propagate(errp, err);
417 }
418 $ python scripts/qapi-commands.py --output-dir="qapi-generated" \
419 --prefix="example-" --input-file=example-schema.json
420 $ cat qapi-generated/example-qapi-visit.h
421 [Uninteresting stuff omitted...]
422
423 #ifndef EXAMPLE_QAPI_VISIT_H
424 #define EXAMPLE_QAPI_VISIT_H
425
426 [Visitors for builtin types omitted...]
427
428 void visit_type_UserDefOne(Visitor *m, UserDefOne **obj, const char *name, Error **errp);
429 void visit_type_UserDefOneList(Visitor *m, UserDefOneList **obj, const char *name, Error **errp);
430
431 #endif
432
433 === scripts/qapi-commands.py ===
434
435 Used to generate the marshaling/dispatch functions for the commands defined
436 in the schema. The following files are generated:
437
438 $(prefix)qmp-marshal.c: command marshal/dispatch functions for each
439 QMP command defined in the schema. Functions
440 generated by qapi-visit.py are used to
441 convert QObjects received from the wire into
442 function parameters, and uses the same
443 visitor functions to convert native C return
444 values to QObjects from transmission back
445 over the wire.
446
447 $(prefix)qmp-commands.h: Function prototypes for the QMP commands
448 specified in the schema.
449
450 Example:
451
452 $ python scripts/qapi-commands.py --output-dir="qapi-generated"
453 --prefix="example-" --input-file=example-schema.json
454 $ cat qapi-generated/example-qmp-marshal.c
455 [Uninteresting stuff omitted...]
456
457 static void qmp_marshal_output_my_command(UserDefOne *ret_in, QObject **ret_out, Error **errp)
458 {
459 Error *local_err = NULL;
460 QmpOutputVisitor *mo = qmp_output_visitor_new();
461 QapiDeallocVisitor *md;
462 Visitor *v;
463
464 v = qmp_output_get_visitor(mo);
465 visit_type_UserDefOne(v, &ret_in, "unused", &local_err);
466 if (local_err) {
467 goto out;
468 }
469 *ret_out = qmp_output_get_qobject(mo);
470
471 out:
472 error_propagate(errp, local_err);
473 qmp_output_visitor_cleanup(mo);
474 md = qapi_dealloc_visitor_new();
475 v = qapi_dealloc_get_visitor(md);
476 visit_type_UserDefOne(v, &ret_in, "unused", NULL);
477 qapi_dealloc_visitor_cleanup(md);
478 }
479
480 static void qmp_marshal_input_my_command(QDict *args, QObject **ret, Error **errp)
481 {
482 Error *local_err = NULL;
483 UserDefOne *retval = NULL;
484 QmpInputVisitor *mi = qmp_input_visitor_new_strict(QOBJECT(args));
485 QapiDeallocVisitor *md;
486 Visitor *v;
487 UserDefOne *arg1 = NULL;
488
489 v = qmp_input_get_visitor(mi);
490 visit_type_UserDefOne(v, &arg1, "arg1", &local_err);
491 if (local_err) {
492 goto out;
493 }
494
495 retval = qmp_my_command(arg1, &local_err);
496 if (local_err) {
497 goto out;
498 }
499
500 qmp_marshal_output_my_command(retval, ret, &local_err);
501
502 out:
503 error_propagate(errp, local_err);
504 qmp_input_visitor_cleanup(mi);
505 md = qapi_dealloc_visitor_new();
506 v = qapi_dealloc_get_visitor(md);
507 visit_type_UserDefOne(v, &arg1, "arg1", NULL);
508 qapi_dealloc_visitor_cleanup(md);
509 return;
510 }
511
512 static void qmp_init_marshal(void)
513 {
514 qmp_register_command("my-command", qmp_marshal_input_my_command, QCO_NO_OPTIONS);
515 }
516
517 qapi_init(qmp_init_marshal);
518 $ cat qapi-generated/example-qmp-commands.h
519 [Uninteresting stuff omitted...]
520
521 #ifndef EXAMPLE_QMP_COMMANDS_H
522 #define EXAMPLE_QMP_COMMANDS_H
523
524 #include "example-qapi-types.h"
525 #include "qapi/qmp/qdict.h"
526 #include "qapi/error.h"
527
528 UserDefOne *qmp_my_command(UserDefOne *arg1, Error **errp);
529
530 #endif
531
532 === scripts/qapi-event.py ===
533
534 Used to generate the event-related C code defined by a schema. The
535 following files are created:
536
537 $(prefix)qapi-event.h - Function prototypes for each event type, plus an
538 enumeration of all event names
539 $(prefix)qapi-event.c - Implementation of functions to send an event
540
541 Example:
542
543 $ python scripts/qapi-event.py --output-dir="qapi-generated"
544 --prefix="example-" --input-file=example-schema.json
545 $ cat qapi-generated/example-qapi-event.c
546 [Uninteresting stuff omitted...]
547
548 void qapi_event_send_my_event(Error **errp)
549 {
550 QDict *qmp;
551 Error *local_err = NULL;
552 QMPEventFuncEmit emit;
553 emit = qmp_event_get_func_emit();
554 if (!emit) {
555 return;
556 }
557
558 qmp = qmp_event_build_dict("MY_EVENT");
559
560 emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp, &local_err);
561
562 error_propagate(errp, local_err);
563 QDECREF(qmp);
564 }
565
566 const char *EXAMPLE_QAPIEvent_lookup[] = {
567 "MY_EVENT",
568 NULL,
569 };
570 $ cat qapi-generated/example-qapi-event.h
571 [Uninteresting stuff omitted...]
572
573 #ifndef EXAMPLE_QAPI_EVENT_H
574 #define EXAMPLE_QAPI_EVENT_H
575
576 #include "qapi/error.h"
577 #include "qapi/qmp/qdict.h"
578 #include "example-qapi-types.h"
579
580
581 void qapi_event_send_my_event(Error **errp);
582
583 extern const char *EXAMPLE_QAPIEvent_lookup[];
584 typedef enum EXAMPLE_QAPIEvent
585 {
586 EXAMPLE_QAPI_EVENT_MY_EVENT = 0,
587 EXAMPLE_QAPI_EVENT_MAX = 1,
588 } EXAMPLE_QAPIEvent;
589
590 #endif