qapi-code-gen.txt 48 KB

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