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