]> git.proxmox.com Git - mirror_qemu.git/blob - docs/qapi-code-gen.txt
qapi: Reserve '*List' type names for list types
[mirror_qemu.git] / docs / qapi-code-gen.txt
1 = How to use the QAPI code generator =
2
3 Copyright IBM Corp. 2011
4 Copyright (C) 2012-2015 Red Hat, Inc.
5
6 This work is licensed under the terms of the GNU GPL, version 2 or
7 later. See the COPYING file in the top-level directory.
8
9 == Introduction ==
10
11 QAPI is a native C API within QEMU which provides management-level
12 functionality to internal and external users. For external
13 users/processes, this interface is made available by a JSON-based wire
14 format for the QEMU Monitor Protocol (QMP) for controlling qemu, as
15 well as the QEMU Guest Agent (QGA) for communicating with the guest.
16 The remainder of this document uses "Client JSON Protocol" when
17 referring to the wire contents of a QMP or QGA connection.
18
19 To map Client JSON Protocol interfaces to the native C QAPI
20 implementations, a JSON-based schema is used to define types and
21 function signatures, and a set of scripts is used to generate types,
22 signatures, and marshaling/dispatch code. This document will describe
23 how the schemas, scripts, and resulting code are used.
24
25
26 == QMP/Guest agent schema ==
27
28 A QAPI schema file is designed to be loosely based on JSON
29 (http://www.ietf.org/rfc/rfc7159.txt) with changes for quoting style
30 and the use of comments; a QAPI schema file is then parsed by a python
31 code generation program. A valid QAPI schema consists of a series of
32 top-level expressions, with no commas between them. Where
33 dictionaries (JSON objects) are used, they are parsed as python
34 OrderedDicts so that ordering is preserved (for predictable layout of
35 generated C structs and parameter lists). Ordering doesn't matter
36 between top-level expressions or the keys within an expression, but
37 does matter within dictionary values for 'data' and 'returns' members
38 of a single expression. QAPI schema input is written using 'single
39 quotes' instead of JSON's "double quotes" (in contrast, Client JSON
40 Protocol uses no comments, and while input accepts 'single quotes' as
41 an extension, output is strict JSON using only "double quotes"). As
42 in JSON, trailing commas are not permitted in arrays or dictionaries.
43 Input must be ASCII (although QMP supports full Unicode strings, the
44 QAPI parser does not). At present, there is no place where a QAPI
45 schema requires the use of JSON numbers or null.
46
47 Comments are allowed; anything between an unquoted # and the following
48 newline is ignored. Although there is not yet a documentation
49 generator, a form of stylized comments has developed for consistently
50 documenting details about an expression and when it was added to the
51 schema. The documentation is delimited between two lines of ##, then
52 the first line names the expression, an optional overview is provided,
53 then individual documentation about each member of 'data' is provided,
54 and finally, a 'Since: x.y.z' tag lists the release that introduced
55 the expression. Optional fields are tagged with the phrase
56 '#optional', often with their default value; and extensions added
57 after the expression was first released are also given a '(since
58 x.y.z)' comment. For example:
59
60 ##
61 # @BlockStats:
62 #
63 # Statistics of a virtual block device or a block backing device.
64 #
65 # @device: #optional If the stats are for a virtual block device, the name
66 # corresponding to the virtual block device.
67 #
68 # @stats: A @BlockDeviceStats for the device.
69 #
70 # @parent: #optional This describes the file block device if it has one.
71 #
72 # @backing: #optional This describes the backing block device if it has one.
73 # (Since 2.0)
74 #
75 # Since: 0.14.0
76 ##
77 { 'struct': 'BlockStats',
78 'data': {'*device': 'str', 'stats': 'BlockDeviceStats',
79 '*parent': 'BlockStats',
80 '*backing': 'BlockStats'} }
81
82 The schema sets up a series of types, as well as commands and events
83 that will use those types. Forward references are allowed: the parser
84 scans in two passes, where the first pass learns all type names, and
85 the second validates the schema and generates the code. This allows
86 the definition of complex structs that can have mutually recursive
87 types, and allows for indefinite nesting of Client JSON Protocol that
88 satisfies the schema. A type name should not be defined more than
89 once. It is permissible for the schema to contain additional types
90 not used by any commands or events in the Client JSON Protocol, for
91 the side effect of generated C code used internally.
92
93 There are seven top-level expressions recognized by the parser:
94 'include', 'command', 'struct', 'enum', 'union', 'alternate', and
95 'event'. There are several groups of types: simple types (a number of
96 built-in types, such as 'int' and 'str'; as well as enumerations),
97 complex types (structs and two flavors of unions), and alternate types
98 (a choice between other types). The 'command' and 'event' expressions
99 can refer to existing types by name, or list an anonymous type as a
100 dictionary. Listing a type name inside an array refers to a
101 single-dimension array of that type; multi-dimension arrays are not
102 directly supported (although an array of a complex struct that
103 contains an array member is possible).
104
105 Types, commands, and events share a common namespace. Therefore,
106 generally speaking, type definitions should always use CamelCase for
107 user-defined type names, while built-in types are lowercase. Type
108 definitions should not end in 'Kind', as this namespace is used for
109 creating implicit C enums for visiting union types, or in 'List', as
110 this namespace is used for creating array types. Command names,
111 and field names within a type, should be all lower case with words
112 separated by a hyphen. However, some existing older commands and
113 complex types use underscore; when extending such expressions,
114 consistency is preferred over blindly avoiding underscore. Event
115 names should be ALL_CAPS with words separated by underscore.
116
117 Any name (command, event, type, field, or enum value) beginning with
118 "x-" is marked experimental, and may be withdrawn or changed
119 incompatibly in a future release. Downstream vendors may add
120 extensions; such extensions should begin with a prefix matching
121 "__RFQDN_" (for the reverse-fully-qualified-domain-name of the
122 vendor), even if the rest of the name uses dash (example:
123 __com.redhat_drive-mirror). Other than downstream extensions (with
124 leading underscore and the use of dots), all names should begin with a
125 letter, and contain only ASCII letters, digits, dash, and underscore.
126 It is okay to reuse names that match C keywords; the generator will
127 rename a field named "default" in the QAPI to "q_default" in the
128 generated C code.
129
130 In the rest of this document, usage lines are given for each
131 expression type, with literal strings written in lower case and
132 placeholders written in capitals. If a literal string includes a
133 prefix of '*', that key/value pair can be omitted from the expression.
134 For example, a usage statement that includes '*base':STRUCT-NAME
135 means that an expression has an optional key 'base', which if present
136 must have a value that forms a struct name.
137
138
139 === Built-in Types ===
140
141 The following types are predefined, and map to C as follows:
142
143 Schema C JSON
144 str char * any JSON string, UTF-8
145 number double any JSON number
146 int int64_t a JSON number without fractional part
147 that fits into the C integer type
148 int8 int8_t likewise
149 int16 int16_t likewise
150 int32 int32_t likewise
151 int64 int64_t likewise
152 uint8 uint8_t likewise
153 uint16 uint16_t likewise
154 uint32 uint32_t likewise
155 uint64 uint64_t likewise
156 size uint64_t like uint64_t, except StringInputVisitor
157 accepts size suffixes
158 bool bool JSON true or false
159 any QObject * any JSON value
160
161
162 === Includes ===
163
164 Usage: { 'include': STRING }
165
166 The QAPI schema definitions can be modularized using the 'include' directive:
167
168 { 'include': 'path/to/file.json' }
169
170 The directive is evaluated recursively, and include paths are relative to the
171 file using the directive. Multiple includes of the same file are
172 idempotent. No other keys should appear in the expression, and the include
173 value should be a string.
174
175 As a matter of style, it is a good idea to have all files be
176 self-contained, but at the moment, nothing prevents an included file
177 from making a forward reference to a type that is only introduced by
178 an outer file. The parser may be made stricter in the future to
179 prevent incomplete include files.
180
181
182 === Struct types ===
183
184 Usage: { 'struct': STRING, 'data': DICT, '*base': STRUCT-NAME }
185
186 A struct is a dictionary containing a single 'data' key whose
187 value is a dictionary. This corresponds to a struct in C or an Object
188 in JSON. Each value of the 'data' dictionary must be the name of a
189 type, or a one-element array containing a type name. An example of a
190 struct is:
191
192 { 'struct': 'MyType',
193 'data': { 'member1': 'str', 'member2': 'int', '*member3': 'str' } }
194
195 The use of '*' as a prefix to the name means the member is optional in
196 the corresponding JSON protocol usage.
197
198 The default initialization value of an optional argument should not be changed
199 between versions of QEMU unless the new default maintains backward
200 compatibility to the user-visible behavior of the old default.
201
202 With proper documentation, this policy still allows some flexibility; for
203 example, documenting that a default of 0 picks an optimal buffer size allows
204 one release to declare the optimal size at 512 while another release declares
205 the optimal size at 4096 - the user-visible behavior is not the bytes used by
206 the buffer, but the fact that the buffer was optimal size.
207
208 On input structures (only mentioned in the 'data' side of a command), changing
209 from mandatory to optional is safe (older clients will supply the option, and
210 newer clients can benefit from the default); changing from optional to
211 mandatory is backwards incompatible (older clients may be omitting the option,
212 and must continue to work).
213
214 On output structures (only mentioned in the 'returns' side of a command),
215 changing from mandatory to optional is in general unsafe (older clients may be
216 expecting the field, and could crash if it is missing), although it can be done
217 if the only way that the optional argument will be omitted is when it is
218 triggered by the presence of a new input flag to the command that older clients
219 don't know to send. Changing from optional to mandatory is safe.
220
221 A structure that is used in both input and output of various commands
222 must consider the backwards compatibility constraints of both directions
223 of use.
224
225 A struct definition can specify another struct as its base.
226 In this case, the fields of the base type are included as top-level fields
227 of the new struct's dictionary in the Client JSON Protocol wire
228 format. An example definition is:
229
230 { 'struct': 'BlockdevOptionsGenericFormat', 'data': { 'file': 'str' } }
231 { 'struct': 'BlockdevOptionsGenericCOWFormat',
232 'base': 'BlockdevOptionsGenericFormat',
233 'data': { '*backing': 'str' } }
234
235 An example BlockdevOptionsGenericCOWFormat object on the wire could use
236 both fields like this:
237
238 { "file": "/some/place/my-image",
239 "backing": "/some/place/my-backing-file" }
240
241
242 === Enumeration types ===
243
244 Usage: { 'enum': STRING, 'data': ARRAY-OF-STRING }
245 { 'enum': STRING, '*prefix': STRING, 'data': ARRAY-OF-STRING }
246
247 An enumeration type is a dictionary containing a single 'data' key
248 whose value is a list of strings. An example enumeration is:
249
250 { 'enum': 'MyEnum', 'data': [ 'value1', 'value2', 'value3' ] }
251
252 Nothing prevents an empty enumeration, although it is probably not
253 useful. The list of strings should be lower case; if an enum name
254 represents multiple words, use '-' between words. The string 'max' is
255 not allowed as an enum value, and values should not be repeated.
256
257 The enum constants will be named by using a heuristic to turn the
258 type name into a set of underscore separated words. For the example
259 above, 'MyEnum' will turn into 'MY_ENUM' giving a constant name
260 of 'MY_ENUM_VALUE1' for the first value. If the default heuristic
261 does not result in a desirable name, the optional 'prefix' field
262 can be used when defining the enum.
263
264 The enumeration values are passed as strings over the Client JSON
265 Protocol, but are encoded as C enum integral values in generated code.
266 While the C code starts numbering at 0, it is better to use explicit
267 comparisons to enum values than implicit comparisons to 0; the C code
268 will also include a generated enum member ending in _MAX for tracking
269 the size of the enum, useful when using common functions for
270 converting between strings and enum values. Since the wire format
271 always passes by name, it is acceptable to reorder or add new
272 enumeration members in any location without breaking clients of Client
273 JSON Protocol; however, removing enum values would break
274 compatibility. For any struct that has a field that will only contain
275 a finite set of string values, using an enum type for that field is
276 better than open-coding the field to be type 'str'.
277
278
279 === Union types ===
280
281 Usage: { 'union': STRING, 'data': DICT }
282 or: { 'union': STRING, 'data': DICT, 'base': STRUCT-NAME,
283 'discriminator': ENUM-MEMBER-OF-BASE }
284
285 Union types are used to let the user choose between several different
286 variants for an object. There are two flavors: simple (no
287 discriminator or base), flat (both discriminator and base). A union
288 type is defined using a data dictionary as explained in the following
289 paragraphs.
290
291 A simple union type defines a mapping from automatic discriminator
292 values to data types like in this example:
293
294 { 'struct': 'FileOptions', 'data': { 'filename': 'str' } }
295 { 'struct': 'Qcow2Options',
296 'data': { 'backing-file': 'str', 'lazy-refcounts': 'bool' } }
297
298 { 'union': 'BlockdevOptions',
299 'data': { 'file': 'FileOptions',
300 'qcow2': 'Qcow2Options' } }
301
302 In the Client JSON Protocol, a simple union is represented by a
303 dictionary that contains the 'type' field as a discriminator, and a
304 'data' field that is of the specified data type corresponding to the
305 discriminator value, as in these examples:
306
307 { "type": "file", "data" : { "filename": "/some/place/my-image" } }
308 { "type": "qcow2", "data" : { "backing-file": "/some/place/my-image",
309 "lazy-refcounts": true } }
310
311 The generated C code uses a struct containing a union. Additionally,
312 an implicit C enum 'NameKind' is created, corresponding to the union
313 'Name', for accessing the various branches of the union. No branch of
314 the union can be named 'max', as this would collide with the implicit
315 enum. The value for each branch can be of any type.
316
317 A flat union definition specifies a struct as its base, and
318 avoids nesting on the wire. All branches of the union must be
319 complex types, and the top-level fields of the union dictionary on
320 the wire will be combination of fields from both the base type and the
321 appropriate branch type (when merging two dictionaries, there must be
322 no keys in common). The 'discriminator' field must be the name of an
323 enum-typed member of the base struct.
324
325 The following example enhances the above simple union example by
326 adding a common field 'readonly', renaming the discriminator to
327 something more applicable, and reducing the number of {} required on
328 the wire:
329
330 { 'enum': 'BlockdevDriver', 'data': [ 'file', 'qcow2' ] }
331 { 'struct': 'BlockdevCommonOptions',
332 'data': { 'driver': 'BlockdevDriver', 'readonly': 'bool' } }
333 { 'union': 'BlockdevOptions',
334 'base': 'BlockdevCommonOptions',
335 'discriminator': 'driver',
336 'data': { 'file': 'FileOptions',
337 'qcow2': 'Qcow2Options' } }
338
339 Resulting in these JSON objects:
340
341 { "driver": "file", "readonly": true,
342 "filename": "/some/place/my-image" }
343 { "driver": "qcow2", "readonly": false,
344 "backing-file": "/some/place/my-image", "lazy-refcounts": true }
345
346 Notice that in a flat union, the discriminator name is controlled by
347 the user, but because it must map to a base member with enum type, the
348 code generator can ensure that branches exist for all values of the
349 enum (although the order of the keys need not match the declaration of
350 the enum). In the resulting generated C data types, a flat union is
351 represented as a struct with the base member fields included directly,
352 and then a union of structures for each branch of the struct.
353
354 A simple union can always be re-written as a flat union where the base
355 class has a single member named 'type', and where each branch of the
356 union has a struct with a single member named 'data'. That is,
357
358 { 'union': 'Simple', 'data': { 'one': 'str', 'two': 'int' } }
359
360 is identical on the wire to:
361
362 { 'enum': 'Enum', 'data': ['one', 'two'] }
363 { 'struct': 'Base', 'data': { 'type': 'Enum' } }
364 { 'struct': 'Branch1', 'data': { 'data': 'str' } }
365 { 'struct': 'Branch2', 'data': { 'data': 'int' } }
366 { 'union': 'Flat', 'base': 'Base', 'discriminator': 'type',
367 'data': { 'one': 'Branch1', 'two': 'Branch2' } }
368
369
370 === Alternate types ===
371
372 Usage: { 'alternate': STRING, 'data': DICT }
373
374 An alternate type is one that allows a choice between two or more JSON
375 data types (string, integer, number, or object, but currently not
376 array) on the wire. The definition is similar to a simple union type,
377 where each branch of the union names a QAPI type. For example:
378
379 { 'alternate': 'BlockRef',
380 'data': { 'definition': 'BlockdevOptions',
381 'reference': 'str' } }
382
383 Just like for a simple union, an implicit C enum 'NameKind' is created
384 to enumerate the branches for the alternate 'Name'.
385
386 Unlike a union, the discriminator string is never passed on the wire
387 for the Client JSON Protocol. Instead, the value's JSON type serves
388 as an implicit discriminator, which in turn means that an alternate
389 can only express a choice between types represented differently in
390 JSON. If a branch is typed as the 'bool' built-in, the alternate
391 accepts true and false; if it is typed as any of the various numeric
392 built-ins, it accepts a JSON number; if it is typed as a 'str'
393 built-in or named enum type, it accepts a JSON string; and if it is
394 typed as a complex type (struct or union), it accepts a JSON object.
395 Two different complex types, for instance, aren't permitted, because
396 both are represented as a JSON object.
397
398 The example alternate declaration above allows using both of the
399 following example objects:
400
401 { "file": "my_existing_block_device_id" }
402 { "file": { "driver": "file",
403 "readonly": false,
404 "filename": "/tmp/mydisk.qcow2" } }
405
406
407 === Commands ===
408
409 Usage: { 'command': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT,
410 '*returns': TYPE-NAME,
411 '*gen': false, '*success-response': false }
412
413 Commands are defined by using a dictionary containing several members,
414 where three members are most common. The 'command' member is a
415 mandatory string, and determines the "execute" value passed in a
416 Client JSON Protocol command exchange.
417
418 The 'data' argument maps to the "arguments" dictionary passed in as
419 part of a Client JSON Protocol command. The 'data' member is optional
420 and defaults to {} (an empty dictionary). If present, it must be the
421 string name of a complex type, or a dictionary that declares an
422 anonymous type with the same semantics as a 'struct' expression, with
423 one exception noted below when 'gen' is used.
424
425 The 'returns' member describes what will appear in the "return" field
426 of a Client JSON Protocol reply on successful completion of a command.
427 The member is optional from the command declaration; if absent, the
428 "return" field will be an empty dictionary. If 'returns' is present,
429 it must be the string name of a complex or built-in type, a
430 one-element array containing the name of a complex or built-in type,
431 with one exception noted below when 'gen' is used. Although it is
432 permitted to have the 'returns' member name a built-in type or an
433 array of built-in types, any command that does this cannot be extended
434 to return additional information in the future; thus, new commands
435 should strongly consider returning a dictionary-based type or an array
436 of dictionaries, even if the dictionary only contains one field at the
437 present.
438
439 All commands in Client JSON Protocol use a dictionary to report
440 failure, with no way to specify that in QAPI. Where the error return
441 is different than the usual GenericError class in order to help the
442 client react differently to certain error conditions, it is worth
443 documenting this in the comments before the command declaration.
444
445 Some example commands:
446
447 { 'command': 'my-first-command',
448 'data': { 'arg1': 'str', '*arg2': 'str' } }
449 { 'struct': 'MyType', 'data': { '*value': 'str' } }
450 { 'command': 'my-second-command',
451 'returns': [ 'MyType' ] }
452
453 which would validate this Client JSON Protocol transaction:
454
455 => { "execute": "my-first-command",
456 "arguments": { "arg1": "hello" } }
457 <= { "return": { } }
458 => { "execute": "my-second-command" }
459 <= { "return": [ { "value": "one" }, { } ] }
460
461 In rare cases, QAPI cannot express a type-safe representation of a
462 corresponding Client JSON Protocol command. You then have to suppress
463 generation of a marshalling function by including a key 'gen' with
464 boolean value false, and instead write your own function. Please try
465 to avoid adding new commands that rely on this, and instead use
466 type-safe unions. For an example of this usage:
467
468 { 'command': 'netdev_add',
469 'data': {'type': 'str', 'id': 'str'},
470 'gen': false }
471
472 Normally, the QAPI schema is used to describe synchronous exchanges,
473 where a response is expected. But in some cases, the action of a
474 command is expected to change state in a way that a successful
475 response is not possible (although the command will still return a
476 normal dictionary error on failure). When a successful reply is not
477 possible, the command expression should include the optional key
478 'success-response' with boolean value false. So far, only QGA makes
479 use of this field.
480
481
482 === Events ===
483
484 Usage: { 'event': STRING, '*data': COMPLEX-TYPE-NAME-OR-DICT }
485
486 Events are defined with the keyword 'event'. It is not allowed to
487 name an event 'MAX', since the generator also produces a C enumeration
488 of all event names with a generated _MAX value at the end. When
489 'data' is also specified, additional info will be included in the
490 event, with similar semantics to a 'struct' expression. Finally there
491 will be C API generated in qapi-event.h; when called by QEMU code, a
492 message with timestamp will be emitted on the wire.
493
494 An example event is:
495
496 { 'event': 'EVENT_C',
497 'data': { '*a': 'int', 'b': 'str' } }
498
499 Resulting in this JSON object:
500
501 { "event": "EVENT_C",
502 "data": { "b": "test string" },
503 "timestamp": { "seconds": 1267020223, "microseconds": 435656 } }
504
505
506 == Client JSON Protocol introspection ==
507
508 Clients of a Client JSON Protocol commonly need to figure out what
509 exactly the server (QEMU) supports.
510
511 For this purpose, QMP provides introspection via command
512 query-qmp-schema. QGA currently doesn't support introspection.
513
514 query-qmp-schema returns a JSON array of SchemaInfo objects. These
515 objects together describe the wire ABI, as defined in the QAPI schema.
516
517 However, the SchemaInfo can't reflect all the rules and restrictions
518 that apply to QMP. It's interface introspection (figuring out what's
519 there), not interface specification. The specification is in the QAPI
520 schema. To understand how QMP is to be used, you need to study the
521 QAPI schema.
522
523 Like any other command, query-qmp-schema is itself defined in the QAPI
524 schema, along with the SchemaInfo type. This text attempts to give an
525 overview how things work. For details you need to consult the QAPI
526 schema.
527
528 SchemaInfo objects have common members "name" and "meta-type", and
529 additional variant members depending on the value of meta-type.
530
531 Each SchemaInfo object describes a wire ABI entity of a certain
532 meta-type: a command, event or one of several kinds of type.
533
534 SchemaInfo for commands and events have the same name as in the QAPI
535 schema.
536
537 Command and event names are part of the wire ABI, but type names are
538 not. Therefore, the SchemaInfo for types have auto-generated
539 meaningless names. For readability, the examples in this section use
540 meaningful type names instead.
541
542 To examine a type, start with a command or event using it, then follow
543 references by name.
544
545 QAPI schema definitions not reachable that way are omitted.
546
547 The SchemaInfo for a command has meta-type "command", and variant
548 members "arg-type" and "ret-type". On the wire, the "arguments"
549 member of a client's "execute" command must conform to the object type
550 named by "arg-type". The "return" member that the server passes in a
551 success response conforms to the type named by "ret-type".
552
553 If the command takes no arguments, "arg-type" names an object type
554 without members. Likewise, if the command returns nothing, "ret-type"
555 names an object type without members.
556
557 Example: the SchemaInfo for command query-qmp-schema
558
559 { "name": "query-qmp-schema", "meta-type": "command",
560 "arg-type": ":empty", "ret-type": "SchemaInfoList" }
561
562 Type ":empty" is an object type without members, and type
563 "SchemaInfoList" is the array of SchemaInfo type.
564
565 The SchemaInfo for an event has meta-type "event", and variant member
566 "arg-type". On the wire, a "data" member that the server passes in an
567 event conforms to the object type named by "arg-type".
568
569 If the event carries no additional information, "arg-type" names an
570 object type without members. The event may not have a data member on
571 the wire then.
572
573 Each command or event defined with dictionary-valued 'data' in the
574 QAPI schema implicitly defines an object type.
575
576 Example: the SchemaInfo for EVENT_C from section Events
577
578 { "name": "EVENT_C", "meta-type": "event",
579 "arg-type": ":obj-EVENT_C-arg" }
580
581 Type ":obj-EVENT_C-arg" is an implicitly defined object type with
582 the two members from the event's definition.
583
584 The SchemaInfo for struct and union types has meta-type "object".
585
586 The SchemaInfo for a struct type has variant member "members".
587
588 The SchemaInfo for a union type additionally has variant members "tag"
589 and "variants".
590
591 "members" is a JSON array describing the object's common members, if
592 any. Each element is a JSON object with members "name" (the member's
593 name), "type" (the name of its type), and optionally "default". The
594 member is optional if "default" is present. Currently, "default" can
595 only have value null. Other values are reserved for future
596 extensions.
597
598 Example: the SchemaInfo for MyType from section Struct types
599
600 { "name": "MyType", "meta-type": "object",
601 "members": [
602 { "name": "member1", "type": "str" },
603 { "name": "member2", "type": "int" },
604 { "name": "member3", "type": "str", "default": null } ] }
605
606 "tag" is the name of the common member serving as type tag.
607 "variants" is a JSON array describing the object's variant members.
608 Each element is a JSON object with members "case" (the value of type
609 tag this element applies to) and "type" (the name of an object type
610 that provides the variant members for this type tag value).
611
612 Example: the SchemaInfo for flat union BlockdevOptions from section
613 Union types
614
615 { "name": "BlockdevOptions", "meta-type": "object",
616 "members": [
617 { "name": "driver", "type": "BlockdevDriver" },
618 { "name": "readonly", "type": "bool"} ],
619 "tag": "driver",
620 "variants": [
621 { "case": "file", "type": "FileOptions" },
622 { "case": "qcow2", "type": "Qcow2Options" } ] }
623
624 Note that base types are "flattened": its members are included in the
625 "members" array.
626
627 A simple union implicitly defines an enumeration type for its implicit
628 discriminator (called "type" on the wire, see section Union types).
629
630 A simple union implicitly defines an object type for each of its
631 variants.
632
633 Example: the SchemaInfo for simple union BlockdevOptions from section
634 Union types
635
636 { "name": "BlockdevOptions", "meta-type": "object",
637 "members": [
638 { "name": "kind", "type": "BlockdevOptionsKind" } ],
639 "tag": "type",
640 "variants": [
641 { "case": "file", "type": ":obj-FileOptions-wrapper" },
642 { "case": "qcow2", "type": ":obj-Qcow2Options-wrapper" } ] }
643
644 Enumeration type "BlockdevOptionsKind" and the object types
645 ":obj-FileOptions-wrapper", ":obj-Qcow2Options-wrapper" are
646 implicitly defined.
647
648 The SchemaInfo for an alternate type has meta-type "alternate", and
649 variant member "members". "members" is a JSON array. Each element is
650 a JSON object with member "type", which names a type. Values of the
651 alternate type conform to exactly one of its member types.
652
653 Example: the SchemaInfo for BlockRef from section Alternate types
654
655 { "name": "BlockRef", "meta-type": "alternate",
656 "members": [
657 { "type": "BlockdevOptions" },
658 { "type": "str" } ] }
659
660 The SchemaInfo for an array type has meta-type "array", and variant
661 member "element-type", which names the array's element type. Array
662 types are implicitly defined.
663
664 Example: the SchemaInfo for ['str']
665
666 { "name": "strList", "meta-type": "array",
667 "element-type": "str" }
668
669 The SchemaInfo for an enumeration type has meta-type "enum" and
670 variant member "values".
671
672 Example: the SchemaInfo for MyEnum from section Enumeration types
673
674 { "name": "MyEnum", "meta-type": "enum",
675 "values": [ "value1", "value2", "value3" ] }
676
677 The SchemaInfo for a built-in type has the same name as the type in
678 the QAPI schema (see section Built-in Types), with one exception
679 detailed below. It has variant member "json-type" that shows how
680 values of this type are encoded on the wire.
681
682 Example: the SchemaInfo for str
683
684 { "name": "str", "meta-type": "builtin", "json-type": "string" }
685
686 The QAPI schema supports a number of integer types that only differ in
687 how they map to C. They are identical as far as SchemaInfo is
688 concerned. Therefore, they get all mapped to a single type "int" in
689 SchemaInfo.
690
691 As explained above, type names are not part of the wire ABI. Not even
692 the names of built-in types. Clients should examine member
693 "json-type" instead of hard-coding names of built-in types.
694
695
696 == Code generation ==
697
698 Schemas are fed into four scripts to generate all the code/files that,
699 paired with the core QAPI libraries, comprise everything required to
700 take JSON commands read in by a Client JSON Protocol server, unmarshal
701 the arguments into the underlying C types, call into the corresponding
702 C function, and map the response back to a Client JSON Protocol
703 response to be returned to the user.
704
705 As an example, we'll use the following schema, which describes a single
706 complex user-defined type (which will produce a C struct, along with a list
707 node structure that can be used to chain together a list of such types in
708 case we want to accept/return a list of this type with a command), and a
709 command which takes that type as a parameter and returns the same type:
710
711 $ cat example-schema.json
712 { 'struct': 'UserDefOne',
713 'data': { 'integer': 'int', 'string': 'str' } }
714
715 { 'command': 'my-command',
716 'data': {'arg1': 'UserDefOne'},
717 'returns': 'UserDefOne' }
718
719 { 'event': 'MY_EVENT' }
720
721 === scripts/qapi-types.py ===
722
723 Used to generate the C types defined by a schema. The following files are
724 created:
725
726 $(prefix)qapi-types.h - C types corresponding to types defined in
727 the schema you pass in
728 $(prefix)qapi-types.c - Cleanup functions for the above C types
729
730 The $(prefix) is an optional parameter used as a namespace to keep the
731 generated code from one schema/code-generation separated from others so code
732 can be generated/used from multiple schemas without clobbering previously
733 created code.
734
735 Example:
736
737 $ python scripts/qapi-types.py --output-dir="qapi-generated" \
738 --prefix="example-" example-schema.json
739 $ cat qapi-generated/example-qapi-types.c
740 [Uninteresting stuff omitted...]
741
742 void qapi_free_UserDefOne(UserDefOne *obj)
743 {
744 QapiDeallocVisitor *qdv;
745 Visitor *v;
746
747 if (!obj) {
748 return;
749 }
750
751 qdv = qapi_dealloc_visitor_new();
752 v = qapi_dealloc_get_visitor(qdv);
753 visit_type_UserDefOne(v, &obj, NULL, NULL);
754 qapi_dealloc_visitor_cleanup(qdv);
755 }
756
757 void qapi_free_UserDefOneList(UserDefOneList *obj)
758 {
759 QapiDeallocVisitor *qdv;
760 Visitor *v;
761
762 if (!obj) {
763 return;
764 }
765
766 qdv = qapi_dealloc_visitor_new();
767 v = qapi_dealloc_get_visitor(qdv);
768 visit_type_UserDefOneList(v, &obj, NULL, NULL);
769 qapi_dealloc_visitor_cleanup(qdv);
770 }
771 $ cat qapi-generated/example-qapi-types.h
772 [Uninteresting stuff omitted...]
773
774 #ifndef EXAMPLE_QAPI_TYPES_H
775 #define EXAMPLE_QAPI_TYPES_H
776
777 [Built-in types omitted...]
778
779 typedef struct UserDefOne UserDefOne;
780
781 typedef struct UserDefOneList UserDefOneList;
782
783 struct UserDefOne {
784 int64_t integer;
785 char *string;
786 };
787
788 void qapi_free_UserDefOne(UserDefOne *obj);
789
790 struct UserDefOneList {
791 union {
792 UserDefOne *value;
793 uint64_t padding;
794 };
795 UserDefOneList *next;
796 };
797
798 void qapi_free_UserDefOneList(UserDefOneList *obj);
799
800 #endif
801
802 === scripts/qapi-visit.py ===
803
804 Used to generate the visitor functions used to walk through and convert
805 a QObject (as provided by QMP) to a native C data structure and
806 vice-versa, as well as the visitor function used to dealloc a complex
807 schema-defined C type.
808
809 The following files are generated:
810
811 $(prefix)qapi-visit.c: visitor function for a particular C type, used
812 to automagically convert QObjects into the
813 corresponding C type and vice-versa, as well
814 as for deallocating memory for an existing C
815 type
816
817 $(prefix)qapi-visit.h: declarations for previously mentioned visitor
818 functions
819
820 Example:
821
822 $ python scripts/qapi-visit.py --output-dir="qapi-generated"
823 --prefix="example-" example-schema.json
824 $ cat qapi-generated/example-qapi-visit.c
825 [Uninteresting stuff omitted...]
826
827 static void visit_type_UserDefOne_fields(Visitor *v, UserDefOne **obj, Error **errp)
828 {
829 Error *err = NULL;
830
831 visit_type_int(v, &(*obj)->integer, "integer", &err);
832 if (err) {
833 goto out;
834 }
835 visit_type_str(v, &(*obj)->string, "string", &err);
836 if (err) {
837 goto out;
838 }
839
840 out:
841 error_propagate(errp, err);
842 }
843
844 void visit_type_UserDefOne(Visitor *v, UserDefOne **obj, const char *name, Error **errp)
845 {
846 Error *err = NULL;
847
848 visit_start_struct(v, (void **)obj, "UserDefOne", name, sizeof(UserDefOne), &err);
849 if (!err) {
850 if (*obj) {
851 visit_type_UserDefOne_fields(v, obj, errp);
852 }
853 visit_end_struct(v, &err);
854 }
855 error_propagate(errp, err);
856 }
857
858 void visit_type_UserDefOneList(Visitor *v, UserDefOneList **obj, const char *name, Error **errp)
859 {
860 Error *err = NULL;
861 GenericList *i, **prev;
862
863 visit_start_list(v, name, &err);
864 if (err) {
865 goto out;
866 }
867
868 for (prev = (GenericList **)obj;
869 !err && (i = visit_next_list(v, prev, &err)) != NULL;
870 prev = &i) {
871 UserDefOneList *native_i = (UserDefOneList *)i;
872 visit_type_UserDefOne(v, &native_i->value, NULL, &err);
873 }
874
875 error_propagate(errp, err);
876 err = NULL;
877 visit_end_list(v, &err);
878 out:
879 error_propagate(errp, err);
880 }
881 $ cat qapi-generated/example-qapi-visit.h
882 [Uninteresting stuff omitted...]
883
884 #ifndef EXAMPLE_QAPI_VISIT_H
885 #define EXAMPLE_QAPI_VISIT_H
886
887 [Visitors for built-in types omitted...]
888
889 void visit_type_UserDefOne(Visitor *v, UserDefOne **obj, const char *name, Error **errp);
890 void visit_type_UserDefOneList(Visitor *v, UserDefOneList **obj, const char *name, Error **errp);
891
892 #endif
893
894 === scripts/qapi-commands.py ===
895
896 Used to generate the marshaling/dispatch functions for the commands defined
897 in the schema. The following files are generated:
898
899 $(prefix)qmp-marshal.c: command marshal/dispatch functions for each
900 QMP command defined in the schema. Functions
901 generated by qapi-visit.py are used to
902 convert QObjects received from the wire into
903 function parameters, and uses the same
904 visitor functions to convert native C return
905 values to QObjects from transmission back
906 over the wire.
907
908 $(prefix)qmp-commands.h: Function prototypes for the QMP commands
909 specified in the schema.
910
911 Example:
912
913 $ python scripts/qapi-commands.py --output-dir="qapi-generated"
914 --prefix="example-" example-schema.json
915 $ cat qapi-generated/example-qmp-marshal.c
916 [Uninteresting stuff omitted...]
917
918 static void qmp_marshal_output_UserDefOne(UserDefOne *ret_in, QObject **ret_out, Error **errp)
919 {
920 Error *err = NULL;
921 QmpOutputVisitor *qov = qmp_output_visitor_new();
922 QapiDeallocVisitor *qdv;
923 Visitor *v;
924
925 v = qmp_output_get_visitor(qov);
926 visit_type_UserDefOne(v, &ret_in, "unused", &err);
927 if (err) {
928 goto out;
929 }
930 *ret_out = qmp_output_get_qobject(qov);
931
932 out:
933 error_propagate(errp, err);
934 qmp_output_visitor_cleanup(qov);
935 qdv = qapi_dealloc_visitor_new();
936 v = qapi_dealloc_get_visitor(qdv);
937 visit_type_UserDefOne(v, &ret_in, "unused", NULL);
938 qapi_dealloc_visitor_cleanup(qdv);
939 }
940
941 static void qmp_marshal_my_command(QDict *args, QObject **ret, Error **errp)
942 {
943 Error *err = NULL;
944 UserDefOne *retval;
945 QmpInputVisitor *qiv = qmp_input_visitor_new_strict(QOBJECT(args));
946 QapiDeallocVisitor *qdv;
947 Visitor *v;
948 UserDefOne *arg1 = NULL;
949
950 v = qmp_input_get_visitor(qiv);
951 visit_type_UserDefOne(v, &arg1, "arg1", &err);
952 if (err) {
953 goto out;
954 }
955
956 retval = qmp_my_command(arg1, &err);
957 if (err) {
958 goto out;
959 }
960
961 qmp_marshal_output_UserDefOne(retval, ret, &err);
962
963 out:
964 error_propagate(errp, err);
965 qmp_input_visitor_cleanup(qiv);
966 qdv = qapi_dealloc_visitor_new();
967 v = qapi_dealloc_get_visitor(qdv);
968 visit_type_UserDefOne(v, &arg1, "arg1", NULL);
969 qapi_dealloc_visitor_cleanup(qdv);
970 }
971
972 static void qmp_init_marshal(void)
973 {
974 qmp_register_command("my-command", qmp_marshal_my_command, QCO_NO_OPTIONS);
975 }
976
977 qapi_init(qmp_init_marshal);
978 $ cat qapi-generated/example-qmp-commands.h
979 [Uninteresting stuff omitted...]
980
981 #ifndef EXAMPLE_QMP_COMMANDS_H
982 #define EXAMPLE_QMP_COMMANDS_H
983
984 #include "example-qapi-types.h"
985 #include "qapi/qmp/qdict.h"
986 #include "qapi/error.h"
987
988 UserDefOne *qmp_my_command(UserDefOne *arg1, Error **errp);
989
990 #endif
991
992 === scripts/qapi-event.py ===
993
994 Used to generate the event-related C code defined by a schema. The
995 following files are created:
996
997 $(prefix)qapi-event.h - Function prototypes for each event type, plus an
998 enumeration of all event names
999 $(prefix)qapi-event.c - Implementation of functions to send an event
1000
1001 Example:
1002
1003 $ python scripts/qapi-event.py --output-dir="qapi-generated"
1004 --prefix="example-" example-schema.json
1005 $ cat qapi-generated/example-qapi-event.c
1006 [Uninteresting stuff omitted...]
1007
1008 void qapi_event_send_my_event(Error **errp)
1009 {
1010 QDict *qmp;
1011 Error *err = NULL;
1012 QMPEventFuncEmit emit;
1013 emit = qmp_event_get_func_emit();
1014 if (!emit) {
1015 return;
1016 }
1017
1018 qmp = qmp_event_build_dict("MY_EVENT");
1019
1020 emit(EXAMPLE_QAPI_EVENT_MY_EVENT, qmp, &err);
1021
1022 error_propagate(errp, err);
1023 QDECREF(qmp);
1024 }
1025
1026 const char *const example_QAPIEvent_lookup[] = {
1027 [EXAMPLE_QAPI_EVENT_MY_EVENT] = "MY_EVENT",
1028 [EXAMPLE_QAPI_EVENT_MAX] = NULL,
1029 };
1030 $ cat qapi-generated/example-qapi-event.h
1031 [Uninteresting stuff omitted...]
1032
1033 #ifndef EXAMPLE_QAPI_EVENT_H
1034 #define EXAMPLE_QAPI_EVENT_H
1035
1036 #include "qapi/error.h"
1037 #include "qapi/qmp/qdict.h"
1038 #include "example-qapi-types.h"
1039
1040
1041 void qapi_event_send_my_event(Error **errp);
1042
1043 typedef enum example_QAPIEvent {
1044 EXAMPLE_QAPI_EVENT_MY_EVENT = 0,
1045 EXAMPLE_QAPI_EVENT_MAX = 1,
1046 } example_QAPIEvent;
1047
1048 extern const char *const example_QAPIEvent_lookup[];
1049
1050 #endif
1051
1052 === scripts/qapi-introspect.py ===
1053
1054 Used to generate the introspection C code for a schema. The following
1055 files are created:
1056
1057 $(prefix)qmp-introspect.c - Defines a string holding a JSON
1058 description of the schema.
1059 $(prefix)qmp-introspect.h - Declares the above string.
1060
1061 Example:
1062
1063 $ python scripts/qapi-introspect.py --output-dir="qapi-generated"
1064 --prefix="example-" example-schema.json
1065 $ cat qapi-generated/example-qmp-introspect.c
1066 [Uninteresting stuff omitted...]
1067
1068 const char example_qmp_schema_json[] = "["
1069 "{\"arg-type\": \"0\", \"meta-type\": \"event\", \"name\": \"MY_EVENT\"}, "
1070 "{\"arg-type\": \"1\", \"meta-type\": \"command\", \"name\": \"my-command\", \"ret-type\": \"2\"}, "
1071 "{\"members\": [], \"meta-type\": \"object\", \"name\": \"0\"}, "
1072 "{\"members\": [{\"name\": \"arg1\", \"type\": \"2\"}], \"meta-type\": \"object\", \"name\": \"1\"}, "
1073 "{\"members\": [{\"name\": \"integer\", \"type\": \"int\"}, {\"name\": \"string\", \"type\": \"str\"}], \"meta-type\": \"object\", \"name\": \"2\"}, "
1074 "{\"json-type\": \"int\", \"meta-type\": \"builtin\", \"name\": \"int\"}, "
1075 "{\"json-type\": \"string\", \"meta-type\": \"builtin\", \"name\": \"str\"}]";
1076 $ cat qapi-generated/example-qmp-introspect.h
1077 [Uninteresting stuff omitted...]
1078
1079 #ifndef EXAMPLE_QMP_INTROSPECT_H
1080 #define EXAMPLE_QMP_INTROSPECT_H
1081
1082 extern const char example_qmp_schema_json[];
1083
1084 #endif