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