3 # generate python wrappers from the XML API description
9 enums
= {} # { enumType: { enumConstant: enumValue } }
10 lxc_enums
= {} # { enumType: { enumConstant: enumValue } }
11 qemu_enums
= {} # { enumType: { enumConstant: enumValue } }
13 params
= [] # [ (parameName, paramValue)... ]
22 #######################################################################
24 # That part if purely the API acquisition phase from the
25 # libvirt API description
27 #######################################################################
38 "libvirt-domain-snapshot",
51 # Attach parser to an unmarshalling object. return both objects.
53 parser
= xml
.sax
.make_parser()
54 parser
.setContentHandler(target
)
57 class docParser(xml
.sax
.handler
.ContentHandler
):
59 self
._methodname
= None
63 self
.startElement
= self
.start
64 self
.endElement
= self
.end
65 self
.characters
= self
.data
71 def getmethodname(self
):
72 return self
._methodname
76 print("data %s" % text
)
77 self
._data
.append(text
)
79 def cdata(self
, text
):
81 print("data %s" % text
)
82 self
._data
.append(text
)
84 def start(self
, tag
, attrs
):
86 print("start %s, %s" % (tag
, attrs
))
91 self
.function_cond
= None
92 self
.function_args
= []
93 self
.function_descr
= None
94 self
.function_return
= None
95 self
.function_file
= None
96 self
.function_module
= None
97 if 'name' in attrs
.keys():
98 self
.function
= attrs
['name']
99 if 'file' in attrs
.keys():
100 self
.function_file
= attrs
['file']
101 if 'module' in attrs
.keys():
102 self
.function_module
= attrs
['module']
108 if self
.in_function
== 1:
109 self
.function_arg_name
= None
110 self
.function_arg_type
= None
111 self
.function_arg_info
= None
112 if 'name' in attrs
.keys():
113 self
.function_arg_name
= attrs
['name']
114 if self
.function_arg_name
== 'from':
115 self
.function_arg_name
= 'frm'
116 if 'type' in attrs
.keys():
117 self
.function_arg_type
= attrs
['type']
118 if 'info' in attrs
.keys():
119 self
.function_arg_info
= attrs
['info']
120 elif tag
== 'return':
121 if self
.in_function
== 1:
122 self
.function_return_type
= None
123 self
.function_return_info
= None
124 self
.function_return_field
= None
125 if 'type' in attrs
.keys():
126 self
.function_return_type
= attrs
['type']
127 if 'info' in attrs
.keys():
128 self
.function_return_info
= attrs
['info']
129 if 'field' in attrs
.keys():
130 self
.function_return_field
= attrs
['field']
132 # enums come from header files, hence virterror.h
133 if attrs
['file'] in libvirt_headers
+ ["virerror", "virterror"]:
134 enum(attrs
['type'],attrs
['name'],attrs
['value'])
135 elif attrs
['file'] == "libvirt-lxc":
136 lxc_enum(attrs
['type'],attrs
['name'],attrs
['value'])
137 elif attrs
['file'] == "libvirt-qemu":
138 qemu_enum(attrs
['type'],attrs
['name'],attrs
['value'])
140 if "string" in attrs
.keys():
141 params
.append((attrs
['name'], attrs
['string']))
145 print("end %s" % tag
)
146 if tag
== 'function':
147 # fuctions come from source files, hence 'virerror.c'
148 if self
.function
is not None:
149 if self
.function_module
in libvirt_headers
+ \
150 ["event", "virevent", "virerror", "virterror"]:
151 function(self
.function
, self
.function_descr
,
152 self
.function_return
, self
.function_args
,
153 self
.function_file
, self
.function_module
,
155 elif self
.function_module
== "libvirt-lxc":
156 lxc_function(self
.function
, self
.function_descr
,
157 self
.function_return
, self
.function_args
,
158 self
.function_file
, self
.function_module
,
160 elif self
.function_module
== "libvirt-qemu":
161 qemu_function(self
.function
, self
.function_descr
,
162 self
.function_return
, self
.function_args
,
163 self
.function_file
, self
.function_module
,
165 elif self
.function_file
== "python":
166 function(self
.function
, self
.function_descr
,
167 self
.function_return
, self
.function_args
,
168 self
.function_file
, self
.function_module
,
170 elif self
.function_file
== "python-lxc":
171 lxc_function(self
.function
, self
.function_descr
,
172 self
.function_return
, self
.function_args
,
173 self
.function_file
, self
.function_module
,
175 elif self
.function_file
== "python-qemu":
176 qemu_function(self
.function
, self
.function_descr
,
177 self
.function_return
, self
.function_args
,
178 self
.function_file
, self
.function_module
,
182 if self
.in_function
== 1:
183 self
.function_args
.append([self
.function_arg_name
,
184 self
.function_arg_type
,
185 self
.function_arg_info
])
186 elif tag
== 'return':
187 if self
.in_function
== 1:
188 self
.function_return
= [self
.function_return_type
,
189 self
.function_return_info
,
190 self
.function_return_field
]
195 if self
.in_function
== 1:
196 self
.function_descr
= str
201 if self
.in_function
== 1:
202 self
.function_cond
= str
205 def function(name
, desc
, ret
, args
, file, module
, cond
):
207 if onlyOverrides
and name
not in functions
:
209 if name
== "virConnectListDomains":
210 name
= "virConnectListDomainsID"
211 functions
[name
] = (desc
, ret
, args
, file, module
, cond
)
213 def qemu_function(name
, desc
, ret
, args
, file, module
, cond
):
215 if onlyOverrides
and name
not in qemu_functions
:
217 qemu_functions
[name
] = (desc
, ret
, args
, file, module
, cond
)
219 def lxc_function(name
, desc
, ret
, args
, file, module
, cond
):
221 if onlyOverrides
and name
not in lxc_functions
:
223 lxc_functions
[name
] = (desc
, ret
, args
, file, module
, cond
)
225 def enum(type, name
, value
):
226 if type not in enums
:
228 if (name
.startswith('VIR_DOMAIN_EVENT_ID_') or
229 name
.startswith('VIR_NETWORK_EVENT_ID_')):
230 event_ids
.append(name
)
231 if value
== 'VIR_TYPED_PARAM_INT':
233 elif value
== 'VIR_TYPED_PARAM_UINT':
235 elif value
== 'VIR_TYPED_PARAM_LLONG':
237 elif value
== 'VIR_TYPED_PARAM_ULLONG':
239 elif value
== 'VIR_TYPED_PARAM_DOUBLE':
241 elif value
== 'VIR_TYPED_PARAM_BOOLEAN':
243 elif value
== 'VIR_DOMAIN_AFFECT_CURRENT':
245 elif value
== 'VIR_DOMAIN_AFFECT_LIVE':
247 elif value
== 'VIR_DOMAIN_AFFECT_CONFIG':
249 if onlyOverrides
and name
not in enums
[type]:
251 enums
[type][name
] = value
253 def lxc_enum(type, name
, value
):
254 if type not in lxc_enums
:
256 if onlyOverrides
and name
not in lxc_enums
[type]:
258 lxc_enums
[type][name
] = value
260 def qemu_enum(type, name
, value
):
261 if type not in qemu_enums
:
262 qemu_enums
[type] = {}
263 if onlyOverrides
and name
not in qemu_enums
[type]:
265 qemu_enums
[type][name
] = value
268 #######################################################################
270 # Some filtering rukes to drop functions/types which should not
271 # be exposed as-is on the Python interface
273 #######################################################################
275 functions_failed
= []
276 lxc_functions_failed
= []
277 qemu_functions_failed
= []
278 functions_skipped
= [
279 "virConnectListDomains",
281 lxc_functions_skipped
= []
282 qemu_functions_skipped
= []
288 # 'int *': "usually a return type",
289 'virConnectDomainEventCallback': "No function types in python",
290 'virConnectDomainEventGenericCallback': "No function types in python",
291 'virConnectDomainEventRTCChangeCallback': "No function types in python",
292 'virConnectDomainEventWatchdogCallback': "No function types in python",
293 'virConnectDomainEventIOErrorCallback': "No function types in python",
294 'virConnectDomainEventGraphicsCallback': "No function types in python",
295 'virConnectDomainQemuMonitorEventCallback': "No function types in python",
296 'virStreamEventCallback': "No function types in python",
297 'virEventHandleCallback': "No function types in python",
298 'virEventTimeoutCallback': "No function types in python",
299 'virDomainBlockJobInfoPtr': "Not implemented yet",
302 #######################################################################
304 # Table of remapping to/from the python type or class to the C
307 #######################################################################
310 'void': (None, None, None, None),
311 'int': ('i', None, "int", "int"),
312 'long': ('l', None, "long", "long"),
313 'double': ('d', None, "double", "double"),
314 'unsigned int': ('I', None, "int", "int"),
315 'unsigned long': ('l', None, "long", "long"),
316 'long long': ('L', None, "longlong", "long long"),
317 'unsigned long long': ('L', None, "longlong", "long long"),
318 'unsigned char *': ('z', None, "charPtr", "char *"),
319 'char *': ('z', None, "charPtr", "char *"),
320 'const char *': ('z', None, "constcharPtr", "const char *"),
321 'size_t': ('n', None, "size_t", "size_t"),
323 'virDomainPtr': ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
324 'virDomain *': ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
325 'const virDomain *': ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
327 'virNetworkPtr': ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
328 'virNetwork *': ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
329 'const virNetwork *': ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
331 'virNetworkPortPtr': ('O', "virNetworkPort", "virNetworkPortPtr", "virNetworkPortPtr"),
332 'virNetworkPort *': ('O', "virNetworkPort", "virNetworkPortPtr", "virNetworkPortPtr"),
333 'const virNetworkPort *': ('O', "virNetworkPort", "virNetworkPortPtr", "virNetworkPortPtr"),
335 'virInterfacePtr': ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),
336 'virInterface *': ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),
337 'const virInterface *': ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),
339 'virStoragePoolPtr': ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),
340 'virStoragePool *': ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),
341 'const virStoragePool *': ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),
343 'virStorageVolPtr': ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),
344 'virStorageVol *': ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),
345 'const virStorageVol *': ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),
347 'virConnectPtr': ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
348 'virConnect *': ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
349 'const virConnect *': ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
351 'virNodeDevicePtr': ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
352 'virNodeDevice *': ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
353 'const virNodeDevice *': ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
355 'virSecretPtr': ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
356 'virSecret *': ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
357 'const virSecret *': ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
359 'virNWFilterPtr': ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),
360 'virNWFilter *': ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),
361 'const virNWFilter *': ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),
363 'virNWFilterBindingPtr': ('O', "virNWFilterBinding", "virNWFilterBindingPtr", "virNWFilterBindingPtr"),
364 'virNWFilterBinding *': ('O', "virNWFilterBinding", "virNWFilterBindingPtr", "virNWFilterBindingPtr"),
365 'const virNWFilterBinding *': ('O', "virNWFilterBinding", "virNWFilterBindingPtr", "virNWFilterBindingPtr"),
367 'virStreamPtr': ('O', "virStream", "virStreamPtr", "virStreamPtr"),
368 'virStream *': ('O', "virStream", "virStreamPtr", "virStreamPtr"),
369 'const virStream *': ('O', "virStream", "virStreamPtr", "virStreamPtr"),
371 'virDomainSnapshotPtr': ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
372 'virDomainSnapshot *': ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
373 'const virDomainSnapshot *': ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
378 #######################################################################
380 # This part writes the C <-> Python stubs libvirt.[ch] and
381 # the table libvirt-export.c to add when registrering the Python module
383 #######################################################################
385 # Class methods which are written by hand in libvirt.c but the Python-level
386 # code is still automatically generated (so they are not in skip_function()).
388 'virConnectGetVersion',
389 'virConnectGetLibVersion',
390 'virConnectListDomainsID',
391 'virConnectListDefinedDomains',
392 'virConnectListNetworks',
393 'virConnectListDefinedNetworks',
394 'virConnectListSecrets',
395 'virConnectListInterfaces',
396 'virConnectListStoragePools',
397 'virConnectListDefinedStoragePools',
398 'virConnectListStorageVols',
399 'virConnectListDefinedStorageVols',
400 'virConnectListDefinedInterfaces',
401 'virConnectListNWFilters',
402 'virDomainSnapshotListNames',
403 'virDomainSnapshotListChildrenNames',
404 'virConnGetLastError',
408 'virDomainGetControlInfo',
409 'virDomainGetBlockInfo',
410 'virDomainGetJobInfo',
411 'virDomainGetJobStats',
413 'virNodeGetSecurityModel',
414 'virDomainGetSecurityLabel',
415 'virDomainGetSecurityLabelList',
417 'virDomainGetUUIDString',
418 'virDomainLookupByUUID',
420 'virNetworkGetUUIDString',
421 'virNetworkLookupByUUID',
422 'virDomainGetAutostart',
423 'virNetworkGetAutostart',
424 'virDomainBlockStats',
425 'virDomainInterfaceStats',
426 'virDomainMemoryStats',
427 'virNodeGetCellsFreeMemory',
428 'virDomainGetSchedulerType',
429 'virDomainGetSchedulerParameters',
430 'virDomainGetSchedulerParametersFlags',
431 'virDomainSetSchedulerParameters',
432 'virDomainSetSchedulerParametersFlags',
433 'virDomainSetBlkioParameters',
434 'virDomainGetBlkioParameters',
435 'virDomainSetMemoryParameters',
436 'virDomainGetMemoryParameters',
437 'virDomainSetNumaParameters',
438 'virDomainGetNumaParameters',
441 'virDomainPinVcpuFlags',
442 'virDomainGetVcpuPinInfo',
443 'virDomainGetEmulatorPinInfo',
444 'virDomainPinEmulator',
445 'virDomainGetIOThreadInfo',
446 'virDomainPinIOThread',
447 'virDomainSetIOThreadParams',
451 'virSecretGetUUIDString',
452 'virSecretLookupByUUID',
453 'virNWFilterGetUUID',
454 'virNWFilterGetUUIDString',
455 'virNWFilterLookupByUUID',
456 'virStoragePoolGetUUID',
457 'virStoragePoolGetUUIDString',
458 'virStoragePoolLookupByUUID',
459 'virStoragePoolGetInfo',
460 'virStorageVolGetInfo',
461 'virStorageVolGetInfoFlags',
462 'virStoragePoolGetAutostart',
463 'virStoragePoolListVolumes',
464 'virDomainBlockPeek',
465 'virDomainMemoryPeek',
466 'virEventRegisterImpl',
467 'virNodeListDevices',
468 'virNodeDeviceListCaps',
469 'virConnectBaselineCPU',
470 'virDomainRevertToSnapshot',
472 'virNodeGetCPUStats',
473 'virNodeGetMemoryStats',
474 'virDomainGetBlockJobInfo',
475 'virDomainMigrateGetCompressionCache',
476 'virDomainMigrateGetMaxSpeed',
477 'virDomainMigrateGetMaxDowntime',
478 'virDomainBlockStatsFlags',
479 'virDomainSetBlockIoTune',
480 'virDomainGetBlockIoTune',
481 'virDomainSetInterfaceParameters',
482 'virDomainGetInterfaceParameters',
483 'virDomainGetCPUStats',
484 'virDomainGetDiskErrors',
485 'virNodeGetMemoryParameters',
486 'virNodeSetMemoryParameters',
489 'virDomainMigrateToURI3',
490 'virConnectGetCPUModelNames',
491 'virNodeGetFreePages',
492 'virNetworkGetDHCPLeases',
493 'virDomainBlockCopy',
495 'virDomainGetFSInfo',
496 'virDomainInterfaceAddresses',
497 'virDomainGetPerfEvents',
498 'virDomainSetPerfEvents',
499 'virDomainGetGuestVcpus',
500 'virConnectBaselineHypervisorCPU',
501 'virDomainGetLaunchSecurityInfo',
503 'virNetworkPortGetParameters',
504 'virNetworkPortSetParameters',
508 'virDomainLxcOpenNamespace',
512 'virDomainQemuMonitorCommand',
513 'virDomainQemuAgentCommand',
517 # These are functions which the generator skips completly - no python
518 # or C code is generated. Generally should not be used for any more
519 # functions than those already listed
521 'virConnectListDomains', # Python API is called virConectListDomainsID for unknown reasons
522 'virConnSetErrorFunc', # Not used in Python API XXX is this a bug ?
523 'virResetError', # Not used in Python API XXX is this a bug ?
524 'virGetVersion', # Python C code is manually written
525 'virSetErrorFunc', # Python API is called virRegisterErrorHandler for unknown reasons
526 'virConnCopyLastError', # Python API is called virConnGetLastError instead
527 'virCopyLastError', # Python API is called virGetLastError instead
528 'virConnectOpenAuth', # Python C code is manually written
529 'virDefaultErrorFunc', # Python virErrorFuncHandler impl calls this from C
530 'virConnectDomainEventRegister', # overridden in virConnect.py
531 'virConnectDomainEventDeregister', # overridden in virConnect.py
532 'virConnectDomainEventRegisterAny', # overridden in virConnect.py
533 'virConnectDomainEventDeregisterAny', # overridden in virConnect.py
534 'virConnectNetworkEventRegisterAny', # overridden in virConnect.py
535 'virConnectNetworkEventDeregisterAny', # overridden in virConnect.py
536 'virConnectStoragePoolEventRegisterAny', # overridden in virConnect.py
537 'virConnectStoragePoolEventDeregisterAny', # overridden in virConnect.py
538 'virConnectNodeDeviceEventRegisterAny', # overridden in virConnect.py
539 'virConnectNodeDeviceEventDeregisterAny', # overridden in virConnect.py
540 'virConnectSecretEventRegisterAny', # overridden in virConnect.py
541 'virConnectSecretEventDeregisterAny', # overridden in virConnect.py
542 'virSaveLastError', # We have our own python error wrapper
543 'virFreeError', # Only needed if we use virSaveLastError
544 'virConnectListAllDomains', # overridden in virConnect.py
545 'virDomainListAllSnapshots', # overridden in virDomain.py
546 'virDomainSnapshotListAllChildren', # overridden in virDomainSnapshot.py
547 'virConnectListAllStoragePools', # overridden in virConnect.py
548 'virStoragePoolListAllVolumes', # overridden in virStoragePool.py
549 'virConnectListAllNetworks', # overridden in virConnect.py
550 'virNetworkListAllPorts', # overridden in virConnect.py
551 'virConnectListAllInterfaces', # overridden in virConnect.py
552 'virConnectListAllNodeDevices', # overridden in virConnect.py
553 'virConnectListAllNWFilters', # overridden in virConnect.py
554 'virConnectListAllNWFilterBindings', # overridden in virConnect.py
555 'virConnectListAllSecrets', # overridden in virConnect.py
556 'virConnectGetAllDomainStats', # overridden in virConnect.py
557 'virDomainListGetStats', # overriden in virConnect.py
559 'virStreamRecvAll', # Pure python libvirt-override-virStream.py
560 'virStreamSendAll', # Pure python libvirt-override-virStream.py
561 'virStreamRecv', # overridden in libvirt-override-virStream.py
562 'virStreamSend', # overridden in libvirt-override-virStream.py
563 'virStreamRecvHole', # overridden in libvirt-override-virStream.py
564 'virStreamSendHole', # overridden in libvirt-override-virStream.py
565 'virStreamRecvFlags', # overridden in libvirt-override-virStream.py
566 'virStreamSparseRecvAll', # overridden in libvirt-override-virStream.py
567 'virStreamSparseSendAll', # overridden in libvirt-override-virStream.py
569 'virConnectUnregisterCloseCallback', # overridden in virConnect.py
570 'virConnectRegisterCloseCallback', # overridden in virConnect.py
572 'virDomainCreateXMLWithFiles', # overridden in virConnect.py
573 'virDomainCreateWithFiles', # overridden in virDomain.py
575 'virDomainFSFreeze', # overridden in virDomain.py
576 'virDomainFSThaw', # overridden in virDomain.py
577 'virDomainGetTime', # overridden in virDomain.py
578 'virDomainSetTime', # overridden in virDomain.py
580 # 'Ref' functions have no use for bindings users.
589 "virNWFilterBindingRef",
593 "virDomainSnapshotRef",
595 # This functions shouldn't be called via the bindings (and even the docs
596 # contain an explicit warning to that effect). The equivalent should be
597 # implemented in pure python for each class
598 "virDomainGetConnect",
599 "virInterfaceGetConnect",
600 "virNetworkGetConnect",
601 "virNetworkPortGetNetwork",
602 "virSecretGetConnect",
603 "virNWFilterGetConnect",
604 "virStoragePoolGetConnect",
605 "virStorageVolGetConnect",
606 "virDomainSnapshotGetConnect",
607 "virDomainSnapshotGetDomain",
609 # only useful in C code, python code uses dict for typed parameters
610 "virTypedParamsAddBoolean",
611 "virTypedParamsAddDouble",
612 "virTypedParamsAddFromString",
613 "virTypedParamsAddInt",
614 "virTypedParamsAddLLong",
615 "virTypedParamsAddString",
616 "virTypedParamsAddUInt",
617 "virTypedParamsAddULLong",
618 "virTypedParamsClear",
619 "virTypedParamsFree",
621 "virTypedParamsGetBoolean",
622 "virTypedParamsGetDouble",
623 "virTypedParamsGetInt",
624 "virTypedParamsGetLLong",
625 "virTypedParamsGetString",
626 "virTypedParamsGetUInt",
627 "virTypedParamsGetULLong",
629 'virNetworkDHCPLeaseFree', # only useful in C, python code uses list
630 'virDomainStatsRecordListFree', # only useful in C, python uses dict
631 'virDomainFSInfoFree', # only useful in C, python code uses list
632 'virDomainIOThreadInfoFree', # only useful in C, python code uses list
633 'virDomainInterfaceFree', # only useful in C, python code uses list
636 lxc_skip_function
= (
637 "virDomainLxcEnterNamespace",
638 "virDomainLxcEnterSecurityLabel",
640 qemu_skip_function
= (
641 #"virDomainQemuAttach",
642 'virConnectDomainQemuMonitorEventRegister', # overridden in -qemu.py
643 'virConnectDomainQemuMonitorEventDeregister', # overridden in -qemu.py
646 # Generate C code, but skip python impl
647 function_skip_python_impl
= (
648 "virStreamFree", # Needed in custom virStream __del__, but free shouldn't
649 # be exposed in bindings
652 lxc_function_skip_python_impl
= ()
653 qemu_function_skip_python_impl
= ()
655 function_skip_index_one
= (
656 "virDomainRevertToSnapshot",
659 def print_function_wrapper(module
, name
, output
, export
, include
):
664 global qemu_functions
665 global skipped_modules
666 global function_skip_python_impl
669 if module
== "libvirt":
670 (desc
, ret
, args
, file, mod
, cond
) = functions
[name
]
671 if module
== "libvirt-lxc":
672 (desc
, ret
, args
, file, mod
, cond
) = lxc_functions
[name
]
673 if module
== "libvirt-qemu":
674 (desc
, ret
, args
, file, mod
, cond
) = qemu_functions
[name
]
676 print("failed to get function %s infos" % name
)
679 if module
in skipped_modules
:
682 if module
== "libvirt":
683 if name
in skip_function
:
685 if name
in skip_impl
:
686 # Don't delete the function entry in the caller.
688 elif module
== "libvirt-lxc":
689 if name
in lxc_skip_function
:
691 if name
in lxc_skip_impl
:
692 # Don't delete the function entry in the caller.
694 elif module
== "libvirt-qemu":
695 if name
in qemu_skip_function
:
697 if name
in qemu_skip_impl
:
698 # Don't delete the function entry in the caller.
709 # This should be correct
710 if arg
[1][0:6] == "const ":
712 c_args
= c_args
+ " %s %s;\n" % (arg
[1], arg
[0])
713 if arg
[1] in py_types
:
714 (f
, t
, n
, c
) = py_types
[arg
[1]]
718 format_args
= format_args
+ ", &pyobj_%s" % (arg
[0])
719 c_args
= c_args
+ " PyObject *pyobj_%s;\n" % (arg
[0])
720 c_convert
= c_convert
+ \
721 " %s = (%s) Py%s_Get(pyobj_%s);\n" % (arg
[0],
724 format_args
= format_args
+ ", &%s" % (arg
[0])
726 format_args
= format_args
+ ", &py_buffsize%d" % num_bufs
727 c_args
= c_args
+ " int py_buffsize%d;\n" % num_bufs
728 num_bufs
= num_bufs
+ 1
730 c_call
= c_call
+ ", "
731 c_call
= c_call
+ "%s" % (arg
[0])
733 if arg
[1] in skipped_types
:
735 if arg
[1] in unknown_types
:
736 lst
= unknown_types
[arg
[1]]
739 unknown_types
[arg
[1]] = [name
]
742 format
= format
+ ":%s" % (name
)
745 if file == "python_accessor":
746 if args
[1][1] == "char *":
747 c_call
= "\n VIR_FREE(%s->%s);\n" % (
748 args
[0][0], args
[1][0], args
[0][0], args
[1][0])
749 c_call
= c_call
+ " %s->%s = (%s)strdup((const xmlChar *)%s);\n" % (args
[0][0],
750 args
[1][0], args
[1][1], args
[1][0])
752 c_call
= "\n %s->%s = %s;\n" % (args
[0][0], args
[1][0],
755 c_call
= "\n %s(%s);\n" % (name
, c_call
)
756 ret_convert
= " Py_INCREF(Py_None);\n return Py_None;\n"
757 elif ret
[0] in py_types
:
758 (f
, t
, n
, c
) = py_types
[ret
[0]]
759 c_return
= " %s c_retval;\n" % (ret
[0])
760 if file == "python_accessor" and ret
[2] is not None:
761 c_call
= "\n c_retval = %s->%s;\n" % (args
[0][0], ret
[2])
763 c_call
= "\n c_retval = %s(%s);\n" % (name
, c_call
)
764 ret_convert
= " py_retval = libvirt_%sWrap((%s) c_retval);\n" % (n
,c
)
766 ret_convert
= ret_convert
+ " free(c_retval);\n"
767 ret_convert
= ret_convert
+ " return py_retval;\n"
769 if ret
[0] in skipped_types
:
771 if ret
[0] in unknown_types
:
772 lst
= unknown_types
[ret
[0]]
775 unknown_types
[ret
[0]] = [name
]
778 if cond
is not None and cond
!= "":
779 include
.write("#if %s\n" % cond
)
780 export
.write("#if %s\n" % cond
)
781 output
.write("#if %s\n" % cond
)
783 include
.write("PyObject * ")
784 if module
== "libvirt":
785 include
.write("libvirt_%s(PyObject *self, PyObject *args);\n" % (name
))
786 export
.write(" { (char *)\"%s\", libvirt_%s, METH_VARARGS, NULL },\n" %
788 elif module
== "libvirt-lxc":
789 include
.write("libvirt_lxc_%s(PyObject *self, PyObject *args);\n" % (name
))
790 export
.write(" { (char *)\"%s\", libvirt_lxc_%s, METH_VARARGS, NULL },\n" %
792 elif module
== "libvirt-qemu":
793 include
.write("libvirt_qemu_%s(PyObject *self, PyObject *args);\n" % (name
))
794 export
.write(" { (char *)\"%s\", libvirt_qemu_%s, METH_VARARGS, NULL },\n" %
798 # Those have been manually generated
799 if cond
is not None and cond
!= "":
800 include
.write("#endif\n")
801 export
.write("#endif\n")
802 output
.write("#endif\n")
804 if file == "python_accessor" and ret
[0] != "void" and ret
[2] is None:
805 # Those have been manually generated
806 if cond
is not None and cond
!= "":
807 include
.write("#endif\n")
808 export
.write("#endif\n")
809 output
.write("#endif\n")
812 output
.write("PyObject *\n")
813 if module
== "libvirt":
814 output
.write("libvirt_%s(PyObject *self ATTRIBUTE_UNUSED," % (name
))
815 elif module
== "libvirt-lxc":
816 output
.write("libvirt_lxc_%s(PyObject *self ATTRIBUTE_UNUSED," % (name
))
817 elif module
== "libvirt-qemu":
818 output
.write("libvirt_qemu_%s(PyObject *self ATTRIBUTE_UNUSED," % (name
))
819 output
.write(" PyObject *args")
821 output
.write(" ATTRIBUTE_UNUSED")
822 output
.write(") {\n")
824 output
.write(" PyObject *py_retval;\n")
826 output
.write(c_return
)
830 output
.write("\n if (!PyArg_ParseTuple(args, (char *)\"%s\"%s))\n" %
831 (format
, format_args
))
832 output
.write(" return NULL;\n")
834 output
.write(c_convert
+ "\n")
836 output
.write(" LIBVIRT_BEGIN_ALLOW_THREADS;")
838 output
.write(" LIBVIRT_END_ALLOW_THREADS;\n")
839 output
.write(ret_convert
)
840 output
.write("}\n\n")
841 if cond
is not None and cond
!= "":
842 include
.write("#endif /* %s */\n" % cond
)
843 export
.write("#endif /* %s */\n" % cond
)
844 output
.write("#endif /* %s */\n" % cond
)
846 if module
== "libvirt":
847 if name
in function_skip_python_impl
:
849 elif module
== "libvirt-lxc":
850 if name
in lxc_function_skip_python_impl
:
852 elif module
== "libvirt-qemu":
853 if name
in qemu_function_skip_python_impl
:
857 def print_c_pointer(classname
, output
, export
, include
):
858 output
.write("PyObject *\n")
859 output
.write("libvirt_%s_pointer(PyObject *self ATTRIBUTE_UNUSED, PyObject *args)\n" % classname
)
861 output
.write(" %sPtr ptr;\n" % classname
)
862 output
.write(" PyObject *pyptr;\n")
863 output
.write(" PyObject *pylong;\n")
865 output
.write(" if (!PyArg_ParseTuple(args, (char *) \"O\", &pyptr))\n")
866 output
.write(" return NULL;\n")
867 output
.write(" ptr = (%sPtr) Py%s_Get(pyptr);\n" % (classname
, classname
))
868 output
.write(" pylong = PyLong_FromVoidPtr(ptr);\n")
869 output
.write(" return pylong;\n")
873 include
.write("PyObject *libvirt_%s_pointer(PyObject *self, PyObject *args);\n" % classname
)
875 export
.write(" { (char *)\"%s_pointer\", libvirt_%s_pointer, METH_VARARGS, NULL },\n" %
876 (classname
, classname
))
878 def buildStubs(module
, api_xml
):
883 if module
not in ["libvirt", "libvirt-qemu", "libvirt-lxc"]:
884 print("ERROR: Unknown module type: %s" % module
)
887 if module
== "libvirt":
889 funcs_failed
= functions_failed
890 funcs_skipped
= functions_skipped
891 elif module
== "libvirt-lxc":
892 funcs
= lxc_functions
893 funcs_failed
= lxc_functions_failed
894 funcs_skipped
= lxc_functions_skipped
895 elif module
== "libvirt-qemu":
896 funcs
= qemu_functions
897 funcs_failed
= qemu_functions_failed
898 funcs_skipped
= qemu_functions_skipped
904 onlyOverrides
= False
905 (parser
, target
) = getparser()
909 msg
= sys
.exc_info()[1]
910 print(file, ":", msg
)
913 n
= len(list(funcs
.keys()))
915 print("Found %d functions in %s" % ((n
), api_xml
))
917 override_api_xml
= "%s-override-api.xml" % module
918 py_types
['pythonObject'] = ('O', "pythonObject", "pythonObject", "pythonObject")
921 f
= open(override_api_xml
)
925 (parser
, target
) = getparser()
929 msg
= sys
.exc_info()[1]
930 print(file, ":", msg
)
933 # XXX: This is not right, same function already in @functions
934 # will be overwritten.
935 print("Found %d functions in %s" % ((len(list(funcs
.keys())) - n
), override_api_xml
))
940 header_file
= "build/%s.h" % module
941 export_file
= "build/%s-export.c" % module
942 wrapper_file
= "build/%s.c" % module
944 include
= open(header_file
, "w")
945 include
.write("/* Generated by generator.py */\n\n")
947 export
= open(export_file
, "w")
948 export
.write("/* Generated by generator.py */\n\n")
950 wrapper
= open(wrapper_file
, "w")
951 wrapper
.write("/* Generated by generator.py */\n\n")
952 wrapper
.write("#include <Python.h>\n")
953 wrapper
.write("#include <libvirt/" + module
+ ".h>\n")
954 wrapper
.write("#include \"typewrappers.h\"\n")
955 wrapper
.write("#include \"build/" + module
+ ".h\"\n\n")
957 for function
in sorted(funcs
.keys()):
958 # Skip the functions which are not for the module
959 ret
= print_function_wrapper(module
, function
, wrapper
, export
, include
)
962 funcs_failed
.append(function
)
965 skipped
= skipped
+ 1
966 funcs_skipped
.append(function
)
969 nb_wrap
= nb_wrap
+ 1
971 if module
== "libvirt":
972 # Write C pointer conversion functions.
973 for classname
in primary_classes
:
974 print_c_pointer(classname
, wrapper
, export
, include
)
975 # Write define wrappers around event id enums, so that the
976 # preprocessor can see which enums were available.
977 for event_id
in event_ids
:
978 include
.write("#define %s %s\n" % (event_id
, event_id
))
985 print("Generated %d wrapper functions" % nb_wrap
)
988 print("Missing type converters: ")
989 for type in list(unknown_types
.keys()):
990 print("%s:%d " % (type, len(unknown_types
[type])))
992 for f
in funcs_failed
:
993 print("ERROR: failed %s" % f
)
997 if len(unknown_types
) > 0:
1001 #######################################################################
1003 # This part writes part of the Python front-end classes based on
1004 # mapping rules between types and classes and also based on function
1005 # renaming to get consistent function names at the Python level
1007 #######################################################################
1010 # The type automatically remapped to generated classes
1013 "virDomainPtr": ("._o", "virDomain(self,_obj=%s)", "virDomain"),
1014 "virDomain *": ("._o", "virDomain(self, _obj=%s)", "virDomain"),
1015 "virNetworkPtr": ("._o", "virNetwork(self, _obj=%s)", "virNetwork"),
1016 "virNetwork *": ("._o", "virNetwork(self, _obj=%s)", "virNetwork"),
1017 "virNetworkPortPtr": ("._o", "virNetworkPort(self, _obj=%s)", "virNetworkPort"),
1018 "virNetworkPort *": ("._o", "virNetworkPort(self, _obj=%s)", "virNetworkPort"),
1019 "virInterfacePtr": ("._o", "virInterface(self, _obj=%s)", "virInterface"),
1020 "virInterface *": ("._o", "virInterface(self, _obj=%s)", "virInterface"),
1021 "virStoragePoolPtr": ("._o", "virStoragePool(self, _obj=%s)", "virStoragePool"),
1022 "virStoragePool *": ("._o", "virStoragePool(self, _obj=%s)", "virStoragePool"),
1023 "virStorageVolPtr": ("._o", "virStorageVol(self, _obj=%s)", "virStorageVol"),
1024 "virStorageVol *": ("._o", "virStorageVol(self, _obj=%s)", "virStorageVol"),
1025 "virNodeDevicePtr": ("._o", "virNodeDevice(self, _obj=%s)", "virNodeDevice"),
1026 "virNodeDevice *": ("._o", "virNodeDevice(self, _obj=%s)", "virNodeDevice"),
1027 "virSecretPtr": ("._o", "virSecret(self, _obj=%s)", "virSecret"),
1028 "virSecret *": ("._o", "virSecret(self, _obj=%s)", "virSecret"),
1029 "virNWFilterPtr": ("._o", "virNWFilter(self, _obj=%s)", "virNWFilter"),
1030 "virNWFilter *": ("._o", "virNWFilter(self, _obj=%s)", "virNWFilter"),
1031 "virNWFilterBindingPtr": ("._o", "virNWFilterBinding(self, _obj=%s)", "virNWFilterBinding"),
1032 "virNWFilterBinding *": ("._o", "virNWFilterBinding(self, _obj=%s)", "virNWFilterBinding"),
1033 "virStreamPtr": ("._o", "virStream(self, _obj=%s)", "virStream"),
1034 "virStream *": ("._o", "virStream(self, _obj=%s)", "virStream"),
1035 "virConnectPtr": ("._o", "virConnect(_obj=%s)", "virConnect"),
1036 "virConnect *": ("._o", "virConnect(_obj=%s)", "virConnect"),
1037 "virDomainSnapshotPtr": ("._o", "virDomainSnapshot(self,_obj=%s)", "virDomainSnapshot"),
1038 "virDomainSnapshot *": ("._o", "virDomainSnapshot(self, _obj=%s)", "virDomainSnapshot"),
1041 primary_classes
= ["virDomain", "virNetwork", "virNetworkPort",
1042 "virInterface", "virStoragePool", "virStorageVol",
1043 "virConnect", "virNodeDevice", "virSecret",
1044 "virNWFilter", "virNWFilterBinding",
1045 "virStream", "virDomainSnapshot"]
1047 classes_destructors
= {
1048 "virDomain": "virDomainFree",
1049 "virNetwork": "virNetworkFree",
1050 "virNetworkPort": "virNetworkPortFree",
1051 "virInterface": "virInterfaceFree",
1052 "virStoragePool": "virStoragePoolFree",
1053 "virStorageVol": "virStorageVolFree",
1054 "virNodeDevice" : "virNodeDeviceFree",
1055 "virSecret": "virSecretFree",
1056 "virNWFilter": "virNWFilterFree",
1057 "virNWFilterBinding": "virNWFilterBindingFree",
1058 "virDomainSnapshot": "virDomainSnapshotFree",
1059 # We hand-craft __del__ for this one
1060 #"virStream": "virStreamFree",
1063 class_skip_connect_impl
= {
1064 "virConnect" : True,
1067 class_domain_impl
= {
1068 "virDomainSnapshot": True,
1071 functions_noexcept
= {
1072 'virDomainGetID': True,
1073 'virDomainGetName': True,
1074 'virNetworkGetName': True,
1075 'virInterfaceGetName': True,
1076 'virStoragePoolGetName': True,
1077 'virStorageVolGetName': True,
1078 'virStorageVolGetkey': True,
1079 'virNodeDeviceGetName': True,
1080 'virNodeDeviceGetParent': True,
1081 'virSecretGetUsageType': True,
1082 'virSecretGetUsageID': True,
1083 'virNWFilterGetName': True,
1084 'virNWFilterBindingGetFilterName': True,
1085 'virNWFilterBindingGetPortDev': True,
1088 function_classes
= {}
1090 function_classes
["None"] = []
1092 # Functions returning an integral type which need special rules to
1093 # check for errors and raise exceptions.
1094 functions_int_exception_test
= {
1095 'virDomainGetMaxMemory': "%s == 0",
1097 functions_int_default_test
= "%s == -1"
1099 def is_integral_type (name
):
1100 return not re
.search ("^(unsigned)? ?(int|long)$", name
) is None
1102 def is_optional_arg(info
):
1103 return re
.search("^\(?optional\)?", info
) is not None
1105 def is_python_noninteger_type (name
):
1107 return name
[-1:] == "*"
1109 def nameFixup(name
, classe
, type, file):
1110 # avoid a disastrous clash
1111 listname
= classe
+ "List"
1114 if name
[0:l
] == listname
:
1116 func
= func
[0:1].lower() + func
[1:]
1117 elif name
[0:16] == "virNetworkDefine":
1119 func
= func
[0:1].lower() + func
[1:]
1120 elif name
[0:19] == "virNetworkCreateXML":
1122 func
= func
[0:1].lower() + func
[1:]
1123 elif name
[0:16] == "virNetworkLookup":
1125 func
= func
[0:1].lower() + func
[1:]
1126 elif name
[0:23] == "virNetworkPortCreateXML":
1128 func
= func
[0:1].lower() + func
[1:]
1129 elif name
[0:20] == "virNetworkPortLookup":
1131 func
= func
[0:1].lower() + func
[1:]
1132 elif name
[0:18] == "virInterfaceDefine":
1134 func
= func
[0:1].lower() + func
[1:]
1135 elif name
[0:21] == "virInterfaceCreateXML":
1137 func
= func
[0:1].lower() + func
[1:]
1138 elif name
[0:18] == "virInterfaceLookup":
1140 func
= func
[0:1].lower() + func
[1:]
1141 elif name
[0:15] == "virSecretDefine":
1143 func
= func
[0:1].lower() + func
[1:]
1144 elif name
[0:15] == "virSecretLookup":
1146 func
= func
[0:1].lower() + func
[1:]
1147 elif name
[0:27] == "virNWFilterBindingCreateXML":
1149 func
= func
[0:3].lower() + func
[3:]
1150 elif name
[0:24] == "virNWFilterBindingLookup":
1152 func
= func
[0:3].lower() + func
[3:]
1153 elif name
[0:24] == "virNWFilterBindingDefine":
1155 func
= func
[0:3].lower() + func
[3:]
1156 elif name
[0:24] == "virNWFilterBindingLookup":
1158 func
= func
[0:3].lower() + func
[3:]
1159 elif name
[0:17] == "virNWFilterDefine":
1161 func
= func
[0:3].lower() + func
[3:]
1162 elif name
[0:17] == "virNWFilterLookup":
1164 func
= func
[0:3].lower() + func
[3:]
1165 elif name
[0:20] == "virStoragePoolDefine":
1167 func
= func
[0:1].lower() + func
[1:]
1168 elif name
[0:23] == "virStoragePoolCreateXML":
1170 func
= func
[0:1].lower() + func
[1:]
1171 elif name
[0:20] == "virStoragePoolLookup":
1173 func
= func
[0:1].lower() + func
[1:]
1174 elif name
[0:19] == "virStorageVolDefine":
1176 func
= func
[0:1].lower() + func
[1:]
1177 elif name
[0:19] == "virStorageVolLookup":
1179 func
= func
[0:1].lower() + func
[1:]
1180 elif name
[0:20] == "virDomainGetCPUStats":
1182 func
= func
[0:1].lower() + func
[1:]
1183 elif name
[0:24] == "virDomainGetIOThreadInfo":
1185 func
= func
[0:2].lower() + func
[2:]
1186 elif name
[0:18] == "virDomainGetFSInfo":
1188 func
= func
[0:2].lower() + func
[2:]
1189 elif name
[0:12] == "virDomainGet":
1191 func
= func
[0:1].lower() + func
[1:]
1192 elif name
[0:29] == "virDomainSnapshotLookupByName":
1194 func
= func
[0:1].lower() + func
[1:]
1195 elif name
[0:26] == "virDomainSnapshotListNames":
1197 func
= func
[0:1].lower() + func
[1:]
1198 elif name
[0:28] == "virDomainSnapshotNumChildren":
1200 func
= func
[0:1].lower() + func
[1:]
1201 elif name
[0:20] == "virDomainSnapshotNum":
1203 func
= func
[0:1].lower() + func
[1:]
1204 elif name
[0:26] == "virDomainSnapshotCreateXML":
1206 func
= func
[0:1].lower() + func
[1:]
1207 elif name
[0:24] == "virDomainSnapshotCurrent":
1209 func
= func
[0:1].lower() + func
[1:]
1210 elif name
[0:17] == "virDomainSnapshot":
1212 func
= func
[0:1].lower() + func
[1:]
1213 elif name
[0:9] == "virDomain":
1215 func
= func
[0:1].lower() + func
[1:]
1216 elif name
[0:13] == "virNetworkGet":
1218 func
= func
[0:1].lower() + func
[1:]
1219 func
= func
.replace("dHCP", "DHCP")
1220 elif name
[0:14] == "virNetworkPort":
1222 func
= func
[0:1].lower() + func
[1:]
1223 elif name
[0:10] == "virNetwork":
1225 func
= func
[0:1].lower() + func
[1:]
1226 elif name
[0:15] == "virInterfaceGet":
1228 func
= func
[0:1].lower() + func
[1:]
1229 elif name
[0:12] == "virInterface":
1231 func
= func
[0:1].lower() + func
[1:]
1232 elif name
[0:12] == 'virSecretGet':
1234 func
= func
[0:1].lower() + func
[1:]
1235 elif name
[0:9] == 'virSecret':
1237 func
= func
[0:1].lower() + func
[1:]
1238 elif name
[0:21] == 'virNWFilterBindingGet':
1240 func
= func
[0:1].lower() + func
[1:]
1241 elif name
[0:18] == 'virNWFilterBinding':
1243 func
= func
[0:1].lower() + func
[1:]
1244 elif name
[0:14] == 'virNWFilterGet':
1246 func
= func
[0:1].lower() + func
[1:]
1247 elif name
[0:11] == 'virNWFilter':
1249 func
= func
[0:1].lower() + func
[1:]
1250 elif name
[0:12] == 'virStreamNew':
1252 elif name
[0:9] == 'virStream':
1254 func
= func
[0:1].lower() + func
[1:]
1255 elif name
[0:17] == "virStoragePoolGet":
1257 func
= func
[0:1].lower() + func
[1:]
1258 elif name
[0:14] == "virStoragePool":
1260 func
= func
[0:1].lower() + func
[1:]
1261 elif name
[0:16] == "virStorageVolGet":
1263 func
= func
[0:1].lower() + func
[1:]
1264 elif name
[0:13] == "virStorageVol":
1266 func
= func
[0:1].lower() + func
[1:]
1267 elif name
[0:13] == "virNodeDevice":
1268 if name
[13:16] == "Get":
1269 func
= name
[16].lower() + name
[17:]
1270 elif name
[13:19] == "Lookup" or name
[13:19] == "Create":
1271 func
= name
[3].lower() + name
[4:]
1273 func
= name
[13].lower() + name
[14:]
1274 elif name
[0:7] == "virNode":
1276 func
= func
[0:1].lower() + func
[1:]
1277 elif name
[0:10] == "virConnect":
1279 func
= func
[0:1].lower() + func
[1:]
1280 elif name
[0:3] == "xml":
1282 func
= func
[0:1].lower() + func
[1:]
1289 if func
== "uUIDString":
1291 if func
== "oSType":
1293 if func
== "xMLDesc":
1295 if func
== "mACString":
1301 def functionSortKey(info
):
1302 (index
, func
, name
, ret
, args
, filename
, mod
) = info
1303 return func
, filename
1305 def writeDoc(module
, name
, args
, indent
, output
):
1306 if module
== "libvirt":
1308 elif module
== "libvirt-lxc":
1309 funcs
= lxc_functions
1310 elif module
== "libvirt-qemu":
1311 funcs
= qemu_functions
1312 if funcs
[name
][0] is None or funcs
[name
][0] == "":
1314 val
= funcs
[name
][0]
1315 val
= val
.replace("NULL", "None")
1316 output
.write(indent
)
1324 output
.write(indent
)
1326 output
.write(' """\n')
1328 def buildWrappers(module
):
1331 global unknown_types
1333 global function_classes
1336 global primary_classes
1337 global classes_destructors
1338 global functions_noexcept
1340 if not module
== "libvirt":
1341 print("ERROR: Unknown module type: %s" % module
)
1344 for type in list(classes_type
.keys()):
1345 function_classes
[classes_type
[type][2]] = []
1348 # Build the list of C types to look for ordered to start
1349 # with primary classes
1353 ctypes_processed
= {}
1354 classes_processed
= {}
1355 for classe
in primary_classes
:
1356 classes_list
.append(classe
)
1357 classes_processed
[classe
] = ()
1358 for type in list(classes_type
.keys()):
1359 tinfo
= classes_type
[type]
1360 if tinfo
[2] == classe
:
1362 ctypes_processed
[type] = ()
1363 for type in list(classes_type
.keys()):
1364 if type in ctypes_processed
:
1366 tinfo
= classes_type
[type]
1367 if tinfo
[2] not in classes_processed
:
1368 classes_list
.append(tinfo
[2])
1369 classes_processed
[tinfo
[2]] = ()
1372 ctypes_processed
[type] = ()
1374 for name
in list(functions
.keys()):
1376 (desc
, ret
, args
, file, mod
, cond
) = functions
[name
]
1378 classe
= classes_type
[type][2]
1380 if name
[0:3] == "vir" and len(args
) >= 1 and args
[0][1] == type:
1382 func
= nameFixup(name
, classe
, type, file)
1383 info
= (0, func
, name
, ret
, args
, file, mod
)
1384 function_classes
[classe
].append(info
)
1386 elif name
[0:3] == "vir" and len(args
) >= 2 and args
[1][1] == type \
1387 and file != "python_accessor" and not name
in function_skip_index_one
:
1389 func
= nameFixup(name
, classe
, type, file)
1390 info
= (1, func
, name
, ret
, args
, file, mod
)
1391 function_classes
[classe
].append(info
)
1395 func
= nameFixup(name
, "None", file, file)
1396 info
= (0, func
, name
, ret
, args
, file, mod
)
1397 function_classes
['None'].append(info
)
1399 classes_file
= "build/%s.py" % module
1400 extra_file
= "%s-override.py" % module
1403 classes
= open(classes_file
, "w")
1405 if os
.path
.exists(extra_file
):
1406 extra
= open(extra_file
, "r")
1407 classes
.write("#\n")
1408 classes
.write("# WARNING WARNING WARNING WARNING\n")
1409 classes
.write("#\n")
1410 classes
.write("# This file is automatically written by generator.py. Any changes\n")
1411 classes
.write("# made here will be lost.\n")
1412 classes
.write("#\n")
1413 classes
.write("# To change the manually written methods edit " + module
+ "-override.py\n")
1414 classes
.write("# To change the automatically written methods edit generator.py\n")
1415 classes
.write("#\n")
1416 classes
.write("# WARNING WARNING WARNING WARNING\n")
1417 classes
.write("#\n")
1418 if extra
is not None:
1419 classes
.writelines(extra
.readlines())
1420 classes
.write("#\n")
1421 classes
.write("# WARNING WARNING WARNING WARNING\n")
1422 classes
.write("#\n")
1423 classes
.write("# Automatically written part of python bindings for libvirt\n")
1424 classes
.write("#\n")
1425 classes
.write("# WARNING WARNING WARNING WARNING\n")
1426 if extra
is not None:
1429 if "None" in function_classes
:
1430 flist
= function_classes
["None"]
1431 flist
.sort(key
=functionSortKey
)
1434 (index
, func
, name
, ret
, args
, file, mod
) = info
1436 classes
.write("#\n# Functions from module %s\n#\n\n" % file)
1438 classes
.write("def %s(" % func
)
1443 classes
.write("%s" % arg
[0])
1444 if arg
[0] == "flags" or is_optional_arg(arg
[2]):
1445 if is_integral_type(arg
[1]):
1448 classes
.write("=None")
1450 classes
.write("):\n")
1451 writeDoc(module
, name
, args
, ' ', classes
)
1454 if arg
[1] in classes_type
:
1455 classes
.write(" if %s is None: %s__o = None\n" %
1457 classes
.write(" else: %s__o = %s%s\n" %
1458 (arg
[0], arg
[0], classes_type
[arg
[1]][0]))
1459 if ret
[0] != "void":
1460 classes
.write(" ret = ")
1463 classes
.write("libvirtmod.%s(" % name
)
1468 classes
.write("%s" % arg
[0])
1469 if arg
[1] in classes_type
:
1470 classes
.write("__o")
1472 classes
.write(")\n")
1474 if ret
[0] != "void":
1475 if ret
[0] in classes_type
:
1477 # Raise an exception
1479 if name
in functions_noexcept
:
1480 classes
.write(" if ret is None:return None\n")
1483 " if ret is None:raise libvirtError('%s() failed')\n" %
1486 classes
.write(" return ")
1487 classes
.write(classes_type
[ret
[0]][1] % ("ret"))
1490 # For functions returning an integral type there are
1491 # several things that we can do, depending on the
1492 # contents of functions_int_*:
1493 elif is_integral_type (ret
[0]):
1494 if name
not in functions_noexcept
:
1495 if name
in functions_int_exception_test
:
1496 test
= functions_int_exception_test
[name
]
1498 test
= functions_int_default_test
1499 classes
.write ((" if " + test
+
1500 ": raise libvirtError ('%s() failed')\n") %
1502 classes
.write(" return ret\n")
1504 elif is_python_noninteger_type (ret
[0]):
1505 if name
not in functions_noexcept
:
1506 classes
.write ((" if %s is None" +
1507 ": raise libvirtError ('%s() failed')\n") %
1509 classes
.write(" return ret\n")
1512 classes
.write(" return ret\n")
1516 for classname
in classes_list
:
1517 if classname
== "None":
1520 classes
.write("class %s(object):\n" % (classname
))
1521 if classname
in [ "virDomain", "virNetwork", "virInterface", "virStoragePool",
1522 "virStorageVol", "virNodeDevice", "virSecret","virStream",
1523 "virNWFilter", "virNWFilterBinding" ]:
1524 classes
.write(" def __init__(self, conn, _obj=None):\n")
1525 elif classname
in [ 'virDomainSnapshot' ]:
1526 classes
.write(" def __init__(self, dom, _obj=None):\n")
1528 classes
.write(" def __init__(self, _obj=None):\n")
1529 if classname
in [ "virDomain", "virNetwork", "virInterface",
1530 "virNodeDevice", "virSecret", "virStream",
1531 "virNWFilter", "virNWFilterBinding" ]:
1532 classes
.write(" self._conn = conn\n")
1533 elif classname
in [ "virStorageVol", "virStoragePool" ]:
1534 classes
.write(" self._conn = conn\n" + \
1535 " if not isinstance(conn, virConnect):\n" + \
1536 " self._conn = conn._conn\n")
1537 elif classname
in [ "virDomainSnapshot" ]:
1538 classes
.write(" self._dom = dom\n")
1539 classes
.write(" self._conn = dom.connect()\n")
1540 classes
.write(" if type(_obj).__name__ not in [\"PyCapsule\", \"PyCObject\"]:\n")
1541 classes
.write(" raise Exception(\"Expected a wrapped C Object but got %s\" % type(_obj))\n")
1542 classes
.write(" self._o = _obj\n\n")
1544 if classname
in classes_destructors
:
1545 classes
.write(" def __del__(self):\n")
1546 classes
.write(" if self._o is not None:\n")
1547 classes
.write(" libvirtmod.%s(self._o)\n" %
1548 classes_destructors
[classname
])
1549 classes
.write(" self._o = None\n\n")
1550 destruct
=classes_destructors
[classname
]
1552 if classname
not in class_skip_connect_impl
:
1553 # Build python safe 'connect' method
1554 classes
.write(" def connect(self):\n")
1555 classes
.write(" return self._conn\n\n")
1557 if classname
in class_domain_impl
:
1558 classes
.write(" def domain(self):\n")
1559 classes
.write(" return self._dom\n\n")
1561 classes
.write(" def c_pointer(self):\n")
1562 classes
.write(" \"\"\"Get C pointer to underlying object\"\"\"\n")
1563 classes
.write(" return libvirtmod.%s_pointer(self._o)\n\n" %
1566 flist
= function_classes
[classname
]
1567 flist
.sort(key
=functionSortKey
)
1570 (index
, func
, name
, ret
, args
, file, mod
) = info
1572 # Do not provide as method the destructors for the class
1573 # to avoid double free
1575 if name
== destruct
:
1578 if file == "python_accessor":
1579 classes
.write(" # accessors for %s\n" % (classname
))
1581 classes
.write(" #\n")
1582 classes
.write(" # %s functions from module %s\n" % (
1584 classes
.write(" #\n\n")
1586 classes
.write(" def %s(self" % func
)
1590 classes
.write(", %s" % arg
[0])
1591 if arg
[0] == "flags" or is_optional_arg(arg
[2]):
1592 if is_integral_type(arg
[1]):
1595 classes
.write("=None")
1597 classes
.write("):\n")
1598 writeDoc(module
, name
, args
, ' ', classes
)
1601 if arg
[1] in classes_type
:
1603 classes
.write(" if %s is None: %s__o = None\n" %
1605 classes
.write(" else: %s__o = %s%s\n" %
1606 (arg
[0], arg
[0], classes_type
[arg
[1]][0]))
1608 if ret
[0] != "void":
1609 classes
.write(" ret = ")
1613 classes
.write("libvirtmod.%s(" % name
)
1618 classes
.write("%s" % arg
[0])
1619 if arg
[1] in classes_type
:
1620 classes
.write("__o")
1622 classes
.write("self")
1623 if arg
[1] in classes_type
:
1624 classes
.write(classes_type
[arg
[1]][0])
1626 classes
.write(")\n")
1628 if name
== "virConnectClose":
1629 classes
.write(" self._o = None\n")
1631 # For functions returning object types:
1632 if ret
[0] != "void":
1633 if ret
[0] in classes_type
:
1635 # Raise an exception
1637 if name
in functions_noexcept
:
1639 " if ret is None:return None\n")
1641 if classname
== "virConnect":
1643 " if ret is None:raise libvirtError('%s() failed', conn=self)\n" %
1645 elif classname
== "virDomain":
1647 " if ret is None:raise libvirtError('%s() failed', dom=self)\n" %
1649 elif classname
== "virNetwork":
1651 " if ret is None:raise libvirtError('%s() failed', net=self)\n" %
1653 elif classname
== "virInterface":
1655 " if ret is None:raise libvirtError('%s() failed', net=self)\n" %
1657 elif classname
== "virStoragePool":
1659 " if ret is None:raise libvirtError('%s() failed', pool=self)\n" %
1661 elif classname
== "virStorageVol":
1663 " if ret is None:raise libvirtError('%s() failed', vol=self)\n" %
1665 elif classname
== "virDomainSnapshot":
1667 " if ret is None:raise libvirtError('%s() failed', dom=self._dom)\n" %
1671 " if ret is None:raise libvirtError('%s() failed')\n" %
1675 # generate the returned class wrapper for the object
1677 classes
.write(" __tmp = ")
1678 classes
.write(classes_type
[ret
[0]][1] % ("ret"))
1684 classes
.write(" return __tmp\n")
1686 # For functions returning an integral type there
1687 # are several things that we can do, depending on
1688 # the contents of functions_int_*:
1689 elif is_integral_type (ret
[0]):
1690 if name
not in functions_noexcept
:
1691 if name
in functions_int_exception_test
:
1692 test
= functions_int_exception_test
[name
]
1694 test
= functions_int_default_test
1695 if classname
== "virConnect":
1696 classes
.write ((" if " + test
+
1697 ": raise libvirtError ('%s() failed', conn=self)\n") %
1699 elif classname
== "virDomain":
1700 classes
.write ((" if " + test
+
1701 ": raise libvirtError ('%s() failed', dom=self)\n") %
1703 elif classname
== "virNetwork":
1704 classes
.write ((" if " + test
+
1705 ": raise libvirtError ('%s() failed', net=self)\n") %
1707 elif classname
== "virInterface":
1708 classes
.write ((" if " + test
+
1709 ": raise libvirtError ('%s() failed', net=self)\n") %
1711 elif classname
== "virStoragePool":
1712 classes
.write ((" if " + test
+
1713 ": raise libvirtError ('%s() failed', pool=self)\n") %
1715 elif classname
== "virStorageVol":
1716 classes
.write ((" if " + test
+
1717 ": raise libvirtError ('%s() failed', vol=self)\n") %
1720 classes
.write ((" if " + test
+
1721 ": raise libvirtError ('%s() failed')\n") %
1724 classes
.write (" return ret\n")
1726 elif is_python_noninteger_type (ret
[0]):
1727 if name
not in functions_noexcept
:
1728 if classname
== "virConnect":
1729 classes
.write ((" if %s is None" +
1730 ": raise libvirtError ('%s() failed', conn=self)\n") %
1732 elif classname
== "virDomain":
1733 classes
.write ((" if %s is None" +
1734 ": raise libvirtError ('%s() failed', dom=self)\n") %
1736 elif classname
== "virNetwork":
1737 classes
.write ((" if %s is None" +
1738 ": raise libvirtError ('%s() failed', net=self)\n") %
1740 elif classname
== "virInterface":
1741 classes
.write ((" if %s is None" +
1742 ": raise libvirtError ('%s() failed', net=self)\n") %
1744 elif classname
== "virStoragePool":
1745 classes
.write ((" if %s is None" +
1746 ": raise libvirtError ('%s() failed', pool=self)\n") %
1748 elif classname
== "virStorageVol":
1749 classes
.write ((" if %s is None" +
1750 ": raise libvirtError ('%s() failed', vol=self)\n") %
1753 classes
.write ((" if %s is None" +
1754 ": raise libvirtError ('%s() failed')\n") %
1757 classes
.write (" return ret\n")
1759 classes
.write(" return ret\n")
1762 # Append "<classname>.py" to class def, iff it exists
1765 extra
= open("libvirt-override-" + classname
+ ".py", "r")
1766 classes
.write (" #\n")
1767 classes
.write (" # %s methods from %s.py (hand coded)\n" % (classname
,classname
))
1768 classes
.write (" #\n")
1772 # Since we compile with older libvirt, we don't want to pull
1773 # in manually written python methods which call C methods
1774 # that don't exist. This code attempts to detect which
1775 # methods to skip by looking at the libvirtmod.XXXX calls
1777 def shouldSkip(lines
):
1779 offset
= line
.find("libvirtmod.")
1781 func
= line
[offset
+ 11:]
1782 offset
= func
.find("(")
1783 func
= func
[0:offset
]
1784 if func
not in functions_skipped
:
1788 for line
in extra
.readlines():
1789 offset
= line
.find(" def ")
1791 name
= line
[offset
+5:]
1792 offset
= name
.find("(")
1793 name
= name
[0:offset
]
1794 if cached
is not None:
1795 if not shouldSkip(cached
):
1796 classes
.writelines(cached
)
1797 if name
== "__del__":
1803 if cached
is not None:
1807 if not shouldSkip(cached
):
1808 classes
.writelines(cached
)
1815 # Generate enum constants
1817 def enumsSortKey(data
):
1822 value
= float('inf')
1823 return value
, data
[0]
1825 # Resolve only one level of reference
1826 def resolveEnum(enum
, data
):
1827 for name
,val
in enum
.items():
1831 enum
[name
] = data
[val
]
1834 enumvals
= list(enums
.items())
1835 # convert list of dicts to one dict
1837 for type,enum
in enumvals
:
1838 enumData
.update(enum
)
1840 if enumvals
is not None:
1841 enumvals
.sort(key
=lambda x
: x
[0])
1842 for type,enum
in enumvals
:
1843 classes
.write("# %s\n" % type)
1844 items
= list(resolveEnum(enum
, enumData
).items())
1845 items
.sort(key
=enumsSortKey
)
1846 if items
[-1][0].endswith('_LAST'):
1848 for name
,value
in items
:
1849 classes
.write("%s = %s\n" % (name
,value
))
1852 classes
.write("# typed parameter names\n")
1853 for name
, value
in params
:
1854 classes
.write("%s = \"%s\"\n" % (name
, value
))
1858 def qemuBuildWrappers(module
):
1859 global qemu_functions
1861 if not module
== "libvirt-qemu":
1862 print("ERROR: only libvirt-qemu is supported")
1865 extra_file
= "%s-override.py" % module
1868 fd
= open("build/libvirt_qemu.py", "w")
1870 if os
.path
.exists(extra_file
):
1871 extra
= open(extra_file
, "r")
1873 fd
.write("# WARNING WARNING WARNING WARNING\n")
1875 fd
.write("# This file is automatically written by generator.py. Any changes\n")
1876 fd
.write("# made here will be lost.\n")
1878 fd
.write("# To change the manually written methods edit " + module
+ "-override.py\n")
1879 fd
.write("# To change the automatically written methods edit generator.py\n")
1881 fd
.write("# WARNING WARNING WARNING WARNING\n")
1883 fd
.write("# Automatically written part of python bindings for libvirt\n")
1886 fd
.write("import sys\n")
1889 fd
.write(" import libvirtmod_qemu\n")
1890 fd
.write("except ImportError:\n")
1891 fd
.write(" lib_e = sys.exc_info()[1]\n")
1893 fd
.write(" import cygvirtmod_qemu as libvirtmod_qemu\n")
1894 fd
.write(" except ImportError:\n")
1895 fd
.write(" cyg_e = sys.exc_info()[1]\n")
1896 fd
.write(" if str(cyg_e).count(\"No module named\"):\n")
1897 fd
.write(" raise lib_e\n\n")
1899 fd
.write("import libvirt\n\n")
1900 fd
.write("# WARNING WARNING WARNING WARNING\n")
1902 if extra
is not None:
1903 fd
.writelines(extra
.readlines())
1905 if extra
is not None:
1908 fd
.write("# WARNING WARNING WARNING WARNING\n")
1910 fd
.write("#\n# Functions from module %s\n#\n\n" % module
)
1912 # Generate functions directly, no classes
1914 for name
in sorted(qemu_functions
.keys()):
1915 func
= nameFixup(name
, 'None', None, None)
1916 (desc
, ret
, args
, file, mod
, cond
) = qemu_functions
[name
]
1917 fd
.write("def %s(" % func
)
1922 fd
.write("%s" % arg
[0])
1925 writeDoc(module
, name
, args
, ' ', fd
)
1927 if ret
[0] != "void":
1931 fd
.write("libvirtmod_qemu.%s(" % name
)
1937 if arg
[1] == "virConnectPtr":
1942 if arg
[1] in ["virDomainPtr", "virConnectPtr"]:
1943 # FIXME: This might have problem if the function
1944 # has multiple args which are objects.
1945 fd
.write("%s.%s" % (arg
[0], "_o"))
1947 fd
.write("%s" % arg
[0])
1951 if ret
[0] != "void":
1952 fd
.write(" if ret is None: raise libvirt.libvirtError('" + name
+ "() failed')\n")
1953 if ret
[0] == "virDomainPtr":
1954 fd
.write(" __tmp = libvirt.virDomain(" + conn
+ ", _obj=ret)\n")
1955 fd
.write(" return __tmp\n")
1957 fd
.write(" return ret\n")
1962 # Generate enum constants
1964 for type,enum
in sorted(qemu_enums
.items()):
1965 fd
.write("# %s\n" % type)
1966 items
= list(enum
.items())
1967 items
.sort(key
=lambda i
: (int(i
[1]), i
[0]))
1968 for name
,value
in items
:
1969 fd
.write("%s = %s\n" % (name
,value
))
1975 def lxcBuildWrappers(module
):
1976 global lxc_functions
1978 if not module
== "libvirt-lxc":
1979 print("ERROR: only libvirt-lxc is supported")
1982 extra_file
= "%s-override.py" % module
1985 fd
= open("build/libvirt_lxc.py", "w")
1987 if os
.path
.exists(extra_file
):
1988 extra
= open(extra_file
, "r")
1990 fd
.write("# WARNING WARNING WARNING WARNING\n")
1992 fd
.write("# This file is automatically written by generator.py. Any changes\n")
1993 fd
.write("# made here will be lost.\n")
1995 fd
.write("# To change the manually written methods edit " + module
+ "-override.py\n")
1996 fd
.write("# To change the automatically written methods edit generator.py\n")
1998 fd
.write("# WARNING WARNING WARNING WARNING\n")
2000 if extra
is not None:
2001 fd
.writelines(extra
.readlines())
2003 fd
.write("# WARNING WARNING WARNING WARNING\n")
2005 fd
.write("# Automatically written part of python bindings for libvirt\n")
2007 fd
.write("# WARNING WARNING WARNING WARNING\n")
2008 if extra
is not None:
2011 fd
.write("import sys\n")
2014 fd
.write(" import libvirtmod_lxc\n")
2015 fd
.write("except ImportError:\n")
2016 fd
.write(" lib_e = sys.exc_info()[1]\n")
2018 fd
.write(" import cygvirtmod_lxc as libvirtmod_lxc\n")
2019 fd
.write(" except ImportError:\n")
2020 fd
.write(" cyg_e = sys.exc_info()[1]\n")
2021 fd
.write(" if str(cyg_e).count(\"No module named\"):\n")
2022 fd
.write(" raise lib_e\n\n")
2024 fd
.write("import libvirt\n\n")
2025 fd
.write("#\n# Functions from module %s\n#\n\n" % module
)
2027 # Generate functions directly, no classes
2029 for name
in sorted(lxc_functions
.keys()):
2030 func
= nameFixup(name
, 'None', None, None)
2031 (desc
, ret
, args
, file, mod
, cond
) = lxc_functions
[name
]
2032 fd
.write("def %s(" % func
)
2037 fd
.write("%s" % arg
[0])
2040 writeDoc(module
, name
, args
, ' ', fd
)
2042 if ret
[0] != "void":
2046 fd
.write("libvirtmod_lxc.%s(" % name
)
2052 if arg
[1] == "virConnectPtr":
2057 if arg
[1] in ["virDomainPtr", "virConnectPtr"]:
2058 # FIXME: This might have problem if the function
2059 # has multiple args which are objects.
2060 fd
.write("%s.%s" % (arg
[0], "_o"))
2062 fd
.write("%s" % arg
[0])
2066 if ret
[0] != "void":
2067 fd
.write(" if ret is None: raise libvirt.libvirtError('" + name
+ "() failed')\n")
2068 if ret
[0] == "virDomainPtr":
2069 fd
.write(" __tmp = libvirt.virDomain(" + conn
+ ", _obj=ret)\n")
2070 fd
.write(" return __tmp\n")
2072 fd
.write(" return ret\n")
2077 # Generate enum constants
2079 for type,enum
in sorted(lxc_enums
.items()):
2080 fd
.write("# %s\n" % type)
2081 items
= list(enum
.items())
2082 items
.sort(key
=lambda i
: (int(i
[1]), i
[0]))
2083 for name
,value
in items
:
2084 fd
.write("%s = %s\n" % (name
,value
))
2091 if not os
.path
.exists("build"):
2094 if buildStubs(sys
.argv
[1], sys
.argv
[2]) < 0:
2097 if sys
.argv
[1] == "libvirt":
2098 buildWrappers(sys
.argv
[1])
2099 elif sys
.argv
[1] == "libvirt-lxc":
2100 lxcBuildWrappers(sys
.argv
[1])
2101 elif sys
.argv
[1] == "libvirt-qemu":
2102 qemuBuildWrappers(sys
.argv
[1])
2104 print("ERROR: unknown module %s" % sys
.argv
[1])