qapi: Document optional arguments' backwards compatibility
[qemu/ar7.git] / docs / qapi-code-gen.txt
blob26312d84e8421d5e2dbc29f857ebdd09beb030fc
1 = How to use the QAPI code generator =
3 * Note: as of this writing, QMP does not use QAPI. Eventually QMP
4 commands will be converted to use QAPI internally. The following
5 information describes QMP/QAPI as it will exist after the
6 conversion.
8 QAPI is a native C API within QEMU which provides management-level
9 functionality to internal/external users. For external
10 users/processes, this interface is made available by a JSON-based
11 QEMU Monitor protocol that is provided by the QMP server.
13 To map QMP-defined interfaces to the native C QAPI implementations,
14 a JSON-based schema is used to define types and function
15 signatures, and a set of scripts is used to generate types/signatures,
16 and marshaling/dispatch code. The QEMU Guest Agent also uses these
17 scripts, paired with a separate schema, to generate
18 marshaling/dispatch code for the guest agent server running in the
19 guest.
21 This document will describe how the schemas, scripts, and resulting
22 code is used.
25 == QMP/Guest agent schema ==
27 This file defines the types, commands, and events used by QMP.  It should
28 fully describe the interface used by QMP.
30 This file is designed to be loosely based on JSON although it's technically
31 executable Python.  While dictionaries are used, they are parsed as
32 OrderedDicts so that ordering is preserved.
34 There are two basic syntaxes used, type definitions and command definitions.
36 The first syntax defines a type and is represented by a dictionary.  There are
37 three kinds of user-defined types that are supported: complex types,
38 enumeration types and union types.
40 Generally speaking, types definitions should always use CamelCase for the type
41 names. Command names should be all lower case with words separated by a hyphen.
44 === Includes ===
46 The QAPI schema definitions can be modularized using the 'include' directive:
48  { 'include': 'path/to/file.json'}
50 The directive is evaluated recursively, and include paths are relative to the
51 file using the directive.
54 === Complex types ===
56 A complex type is a dictionary containing a single key whose value is a
57 dictionary.  This corresponds to a struct in C or an Object in JSON.  An
58 example of a complex type is:
60  { 'type': 'MyType',
61    'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
63 The use of '*' as a prefix to the name means the member is optional.
65 The default initialization value of an optional argument should not be changed
66 between versions of QEMU unless the new default maintains backward
67 compatibility to the user-visible behavior of the old default.
69 With proper documentation, this policy still allows some flexibility; for
70 example, documenting that a default of 0 picks an optimal buffer size allows
71 one release to declare the optimal size at 512 while another release declares
72 the optimal size at 4096 - the user-visible behavior is not the bytes used by
73 the buffer, but the fact that the buffer was optimal size.
75 On input structures (only mentioned in the 'data' side of a command), changing
76 from mandatory to optional is safe (older clients will supply the option, and
77 newer clients can benefit from the default); changing from optional to
78 mandatory is backwards incompatible (older clients may be omitting the option,
79 and must continue to work).
81 On output structures (only mentioned in the 'returns' side of a command),
82 changing from mandatory to optional is in general unsafe (older clients may be
83 expecting the field, and could crash if it is missing), although it can be done
84 if the only way that the optional argument will be omitted is when it is
85 triggered by the presence of a new input flag to the command that older clients
86 don't know to send.  Changing from optional to mandatory is safe.
88 A structure that is used in both input and output of various commands
89 must consider the backwards compatibility constraints of both directions
90 of use.
92 A complex type definition can specify another complex type as its base.
93 In this case, the fields of the base type are included as top-level fields
94 of the new complex type's dictionary in the QMP wire format. An example
95 definition is:
97  { 'type': 'BlockdevOptionsGenericFormat', 'data': { 'file': 'str' } }
98  { 'type': 'BlockdevOptionsGenericCOWFormat',
99    'base': 'BlockdevOptionsGenericFormat',
100    'data': { '*backing': 'str' } }
102 An example BlockdevOptionsGenericCOWFormat object on the wire could use
103 both fields like this:
105  { "file": "/some/place/my-image",
106    "backing": "/some/place/my-backing-file" }
108 === Enumeration types ===
110 An enumeration type is a dictionary containing a single key whose value is a
111 list of strings.  An example enumeration is:
113  { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
115 === Union types ===
117 Union types are used to let the user choose between several different data
118 types.  A union type is defined using a dictionary as explained in the
119 following paragraphs.
122 A simple union type defines a mapping from discriminator values to data types
123 like in this example:
125  { 'type': 'FileOptions', 'data': { 'filename': 'str' } }
126  { 'type': 'Qcow2Options',
127    'data': { 'backing-file': 'str', 'lazy-refcounts': 'bool' } }
129  { 'union': 'BlockdevOptions',
130    'data': { 'file': 'FileOptions',
131              'qcow2': 'Qcow2Options' } }
133 In the QMP wire format, a simple union is represented by a dictionary that
134 contains the 'type' field as a discriminator, and a 'data' field that is of the
135 specified data type corresponding to the discriminator value:
137  { "type": "qcow2", "data" : { "backing-file": "/some/place/my-image",
138                                "lazy-refcounts": true } }
141 A union definition can specify a complex type as its base. In this case, the
142 fields of the complex type are included as top-level fields of the union
143 dictionary in the QMP wire format. An example definition is:
145  { 'type': 'BlockdevCommonOptions', 'data': { 'readonly': 'bool' } }
146  { 'union': 'BlockdevOptions',
147    'base': 'BlockdevCommonOptions',
148    'data': { 'raw': 'RawOptions',
149              'qcow2': 'Qcow2Options' } }
151 And it looks like this on the wire:
153  { "type": "qcow2",
154    "readonly": false,
155    "data" : { "backing-file": "/some/place/my-image",
156               "lazy-refcounts": true } }
159 Flat union types avoid the nesting on the wire. They are used whenever a
160 specific field of the base type is declared as the discriminator ('type' is
161 then no longer generated). The discriminator must be of enumeration type.
162 The above example can then be modified as follows:
164  { 'enum': 'BlockdevDriver', 'data': [ 'raw', 'qcow2' ] }
165  { 'type': 'BlockdevCommonOptions',
166    'data': { 'driver': 'BlockdevDriver', 'readonly': 'bool' } }
167  { 'union': 'BlockdevOptions',
168    'base': 'BlockdevCommonOptions',
169    'discriminator': 'driver',
170    'data': { 'raw': 'RawOptions',
171              'qcow2': 'Qcow2Options' } }
173 Resulting in this JSON object:
175  { "driver": "qcow2",
176    "readonly": false,
177    "backing-file": "/some/place/my-image",
178    "lazy-refcounts": true }
181 A special type of unions are anonymous unions. They don't form a dictionary in
182 the wire format but allow the direct use of different types in their place. As
183 they aren't structured, they don't have any explicit discriminator but use
184 the (QObject) data type of their value as an implicit discriminator. This means
185 that they are restricted to using only one discriminator value per QObject
186 type. For example, you cannot have two different complex types in an anonymous
187 union, or two different integer types.
189 Anonymous unions are declared using an empty dictionary as their discriminator.
190 The discriminator values never appear on the wire, they are only used in the
191 generated C code. Anonymous unions cannot have a base type.
193  { 'union': 'BlockRef',
194    'discriminator': {},
195    'data': { 'definition': 'BlockdevOptions',
196              'reference': 'str' } }
198 This example allows using both of the following example objects:
200  { "file": "my_existing_block_device_id" }
201  { "file": { "driver": "file",
202              "readonly": false,
203              "filename": "/tmp/mydisk.qcow2" } }
206 === Commands ===
208 Commands are defined by using a list containing three members.  The first
209 member is the command name, the second member is a dictionary containing
210 arguments, and the third member is the return type.
212 An example command is:
214  { 'command': 'my-command',
215    'data': { 'arg1': 'str', '*arg2': 'str' },
216    'returns': 'str' }
219 == Code generation ==
221 Schemas are fed into 3 scripts to generate all the code/files that, paired
222 with the core QAPI libraries, comprise everything required to take JSON
223 commands read in by a QMP/guest agent server, unmarshal the arguments into
224 the underlying C types, call into the corresponding C function, and map the
225 response back to a QMP/guest agent response to be returned to the user.
227 As an example, we'll use the following schema, which describes a single
228 complex user-defined type (which will produce a C struct, along with a list
229 node structure that can be used to chain together a list of such types in
230 case we want to accept/return a list of this type with a command), and a
231 command which takes that type as a parameter and returns the same type:
233     mdroth@illuin:~/w/qemu2.git$ cat example-schema.json
234     { 'type': 'UserDefOne',
235       'data': { 'integer': 'int', 'string': 'str' } }
237     { 'command': 'my-command',
238       'data':    {'arg1': 'UserDefOne'},
239       'returns': 'UserDefOne' }
240     mdroth@illuin:~/w/qemu2.git$
242 === scripts/qapi-types.py ===
244 Used to generate the C types defined by a schema. The following files are
245 created:
247 $(prefix)qapi-types.h - C types corresponding to types defined in
248                         the schema you pass in
249 $(prefix)qapi-types.c - Cleanup functions for the above C types
251 The $(prefix) is an optional parameter used as a namespace to keep the
252 generated code from one schema/code-generation separated from others so code
253 can be generated/used from multiple schemas without clobbering previously
254 created code.
256 Example:
258     mdroth@illuin:~/w/qemu2.git$ python scripts/qapi-types.py \
259       --output-dir="qapi-generated" --prefix="example-" --input-file=example-schema.json
260     mdroth@illuin:~/w/qemu2.git$ cat qapi-generated/example-qapi-types.c
261     /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
263     #include "qapi/qapi-dealloc-visitor.h"
264     #include "example-qapi-types.h"
265     #include "example-qapi-visit.h"
267     void qapi_free_UserDefOne(UserDefOne * obj)
268     {
269         QapiDeallocVisitor *md;
270         Visitor *v;
272         if (!obj) {
273             return;
274         }
276         md = qapi_dealloc_visitor_new();
277         v = qapi_dealloc_get_visitor(md);
278         visit_type_UserDefOne(v, &obj, NULL, NULL);
279         qapi_dealloc_visitor_cleanup(md);
280     }
282     mdroth@illuin:~/w/qemu2.git$ cat qapi-generated/example-qapi-types.h
283     /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
284     #ifndef QAPI_GENERATED_EXAMPLE_QAPI_TYPES
285     #define QAPI_GENERATED_EXAMPLE_QAPI_TYPES
287     #include "qapi/qapi-types-core.h"
289     typedef struct UserDefOne UserDefOne;
291     typedef struct UserDefOneList
292     {
293         UserDefOne *value;
294         struct UserDefOneList *next;
295     } UserDefOneList;
297     struct UserDefOne
298     {
299         int64_t integer;
300         char * string;
301     };
303     void qapi_free_UserDefOne(UserDefOne * obj);
305     #endif
308 === scripts/qapi-visit.py ===
310 Used to generate the visitor functions used to walk through and convert
311 a QObject (as provided by QMP) to a native C data structure and
312 vice-versa, as well as the visitor function used to dealloc a complex
313 schema-defined C type.
315 The following files are generated:
317 $(prefix)qapi-visit.c: visitor function for a particular C type, used
318                        to automagically convert QObjects into the
319                        corresponding C type and vice-versa, as well
320                        as for deallocating memory for an existing C
321                        type
323 $(prefix)qapi-visit.h: declarations for previously mentioned visitor
324                        functions
326 Example:
328     mdroth@illuin:~/w/qemu2.git$ python scripts/qapi-visit.py \
329         --output-dir="qapi-generated" --prefix="example-" --input-file=example-schema.json
330     mdroth@illuin:~/w/qemu2.git$ cat qapi-generated/example-qapi-visit.c
331     /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
333     #include "example-qapi-visit.h"
335     void visit_type_UserDefOne(Visitor *m, UserDefOne ** obj, const char *name, Error **errp)
336     {
337         visit_start_struct(m, (void **)obj, "UserDefOne", name, sizeof(UserDefOne), errp);
338         visit_type_int(m, (obj && *obj) ? &(*obj)->integer : NULL, "integer", errp);
339         visit_type_str(m, (obj && *obj) ? &(*obj)->string : NULL, "string", errp);
340         visit_end_struct(m, errp);
341     }
343     void visit_type_UserDefOneList(Visitor *m, UserDefOneList ** obj, const char *name, Error **errp)
344     {
345         GenericList *i, **prev = (GenericList **)obj;
347         visit_start_list(m, name, errp);
349         for (; (i = visit_next_list(m, prev, errp)) != NULL; prev = &i) {
350             UserDefOneList *native_i = (UserDefOneList *)i;
351             visit_type_UserDefOne(m, &native_i->value, NULL, errp);
352         }
354         visit_end_list(m, errp);
355     }
356     mdroth@illuin:~/w/qemu2.git$ cat qapi-generated/example-qapi-visit.h
357     /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
359     #ifndef QAPI_GENERATED_EXAMPLE_QAPI_VISIT
360     #define QAPI_GENERATED_EXAMPLE_QAPI_VISIT
362     #include "qapi/qapi-visit-core.h"
363     #include "example-qapi-types.h"
365     void visit_type_UserDefOne(Visitor *m, UserDefOne ** obj, const char *name, Error **errp);
366     void visit_type_UserDefOneList(Visitor *m, UserDefOneList ** obj, const char *name, Error **errp);
368     #endif
369     mdroth@illuin:~/w/qemu2.git$
371 (The actual structure of the visit_type_* functions is a bit more complex
372 in order to propagate errors correctly and avoid leaking memory).
374 === scripts/qapi-commands.py ===
376 Used to generate the marshaling/dispatch functions for the commands defined
377 in the schema. The following files are generated:
379 $(prefix)qmp-marshal.c: command marshal/dispatch functions for each
380                         QMP command defined in the schema. Functions
381                         generated by qapi-visit.py are used to
382                         convert QObjects received from the wire into
383                         function parameters, and uses the same
384                         visitor functions to convert native C return
385                         values to QObjects from transmission back
386                         over the wire.
388 $(prefix)qmp-commands.h: Function prototypes for the QMP commands
389                          specified in the schema.
391 Example:
393     mdroth@illuin:~/w/qemu2.git$ cat qapi-generated/example-qmp-marshal.c
394     /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
396     #include "qemu-objects.h"
397     #include "qapi/qmp-core.h"
398     #include "qapi/qapi-visit-core.h"
399     #include "qapi/qmp-output-visitor.h"
400     #include "qapi/qmp-input-visitor.h"
401     #include "qapi/qapi-dealloc-visitor.h"
402     #include "example-qapi-types.h"
403     #include "example-qapi-visit.h"
405     #include "example-qmp-commands.h"
406     static void qmp_marshal_output_my_command(UserDefOne * ret_in, QObject **ret_out, Error **errp)
407     {
408         QapiDeallocVisitor *md = qapi_dealloc_visitor_new();
409         QmpOutputVisitor *mo = qmp_output_visitor_new();
410         Visitor *v;
412         v = qmp_output_get_visitor(mo);
413         visit_type_UserDefOne(v, &ret_in, "unused", errp);
414         v = qapi_dealloc_get_visitor(md);
415         visit_type_UserDefOne(v, &ret_in, "unused", errp);
416         qapi_dealloc_visitor_cleanup(md);
419         *ret_out = qmp_output_get_qobject(mo);
420     }
422     static void qmp_marshal_input_my_command(QmpState *qmp__sess, QDict *args, QObject **ret, Error **errp)
423     {
424         UserDefOne * retval = NULL;
425         QmpInputVisitor *mi;
426         QapiDeallocVisitor *md;
427         Visitor *v;
428         UserDefOne * arg1 = NULL;
430         mi = qmp_input_visitor_new(QOBJECT(args));
431         v = qmp_input_get_visitor(mi);
432         visit_type_UserDefOne(v, &arg1, "arg1", errp);
434         if (error_is_set(errp)) {
435             goto out;
436         }
437         retval = qmp_my_command(arg1, errp);
438         qmp_marshal_output_my_command(retval, ret, errp);
440     out:
441         md = qapi_dealloc_visitor_new();
442         v = qapi_dealloc_get_visitor(md);
443         visit_type_UserDefOne(v, &arg1, "arg1", errp);
444         qapi_dealloc_visitor_cleanup(md);
445         return;
446     }
448     static void qmp_init_marshal(void)
449     {
450         qmp_register_command("my-command", qmp_marshal_input_my_command);
451     }
453     qapi_init(qmp_init_marshal);
454     mdroth@illuin:~/w/qemu2.git$ cat qapi-generated/example-qmp-commands.h
455     /* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
457     #ifndef QAPI_GENERATED_EXAMPLE_QMP_COMMANDS
458     #define QAPI_GENERATED_EXAMPLE_QMP_COMMANDS
460     #include "example-qapi-types.h"
461     #include "error.h"
463     UserDefOne * qmp_my_command(UserDefOne * arg1, Error **errp);
465     #endif
466     mdroth@illuin:~/w/qemu2.git$