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