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