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-checkpoint",
39 "libvirt-domain-snapshot",
52 # Attach parser to an unmarshalling object. return both objects.
54 parser
= xml
.sax
.make_parser()
55 parser
.setContentHandler(target
)
58 class docParser(xml
.sax
.handler
.ContentHandler
):
60 self
._methodname
= None
64 self
.startElement
= self
.start
65 self
.endElement
= self
.end
66 self
.characters
= self
.data
72 def getmethodname(self
):
73 return self
._methodname
77 print("data %s" % text
)
78 self
._data
.append(text
)
80 def cdata(self
, text
):
82 print("data %s" % text
)
83 self
._data
.append(text
)
85 def start(self
, tag
, attrs
):
87 print("start %s, %s" % (tag
, attrs
))
92 self
.function_cond
= None
93 self
.function_args
= []
94 self
.function_descr
= None
95 self
.function_return
= None
96 self
.function_file
= None
97 self
.function_module
= None
98 if 'name' in attrs
.keys():
99 self
.function
= attrs
['name']
100 if 'file' in attrs
.keys():
101 self
.function_file
= attrs
['file']
102 if 'module' in attrs
.keys():
103 self
.function_module
= attrs
['module']
109 if self
.in_function
== 1:
110 self
.function_arg_name
= None
111 self
.function_arg_type
= None
112 self
.function_arg_info
= None
113 if 'name' in attrs
.keys():
114 self
.function_arg_name
= attrs
['name']
115 if self
.function_arg_name
== 'from':
116 self
.function_arg_name
= 'frm'
117 if 'type' in attrs
.keys():
118 self
.function_arg_type
= attrs
['type']
119 if 'info' in attrs
.keys():
120 self
.function_arg_info
= attrs
['info']
121 elif tag
== 'return':
122 if self
.in_function
== 1:
123 self
.function_return_type
= None
124 self
.function_return_info
= None
125 self
.function_return_field
= None
126 if 'type' in attrs
.keys():
127 self
.function_return_type
= attrs
['type']
128 if 'info' in attrs
.keys():
129 self
.function_return_info
= attrs
['info']
130 if 'field' in attrs
.keys():
131 self
.function_return_field
= attrs
['field']
133 # enums come from header files, hence virterror.h
134 if attrs
['file'] in libvirt_headers
+ ["virerror", "virterror"]:
135 enum(attrs
['type'],attrs
['name'],attrs
['value'])
136 elif attrs
['file'] == "libvirt-lxc":
137 lxc_enum(attrs
['type'],attrs
['name'],attrs
['value'])
138 elif attrs
['file'] == "libvirt-qemu":
139 qemu_enum(attrs
['type'],attrs
['name'],attrs
['value'])
141 if "string" in attrs
.keys():
142 params
.append((attrs
['name'], attrs
['string']))
146 print("end %s" % tag
)
147 if tag
== 'function':
148 # fuctions come from source files, hence 'virerror.c'
149 if self
.function
is not None:
150 if self
.function_module
in libvirt_headers
+ \
151 ["event", "virevent", "virerror", "virterror"]:
152 function(self
.function
, self
.function_descr
,
153 self
.function_return
, self
.function_args
,
154 self
.function_file
, self
.function_module
,
156 elif self
.function_module
== "libvirt-lxc":
157 lxc_function(self
.function
, self
.function_descr
,
158 self
.function_return
, self
.function_args
,
159 self
.function_file
, self
.function_module
,
161 elif self
.function_module
== "libvirt-qemu":
162 qemu_function(self
.function
, self
.function_descr
,
163 self
.function_return
, self
.function_args
,
164 self
.function_file
, self
.function_module
,
166 elif self
.function_file
== "python":
167 function(self
.function
, self
.function_descr
,
168 self
.function_return
, self
.function_args
,
169 self
.function_file
, self
.function_module
,
171 elif self
.function_file
== "python-lxc":
172 lxc_function(self
.function
, self
.function_descr
,
173 self
.function_return
, self
.function_args
,
174 self
.function_file
, self
.function_module
,
176 elif self
.function_file
== "python-qemu":
177 qemu_function(self
.function
, self
.function_descr
,
178 self
.function_return
, self
.function_args
,
179 self
.function_file
, self
.function_module
,
183 if self
.in_function
== 1:
184 self
.function_args
.append([self
.function_arg_name
,
185 self
.function_arg_type
,
186 self
.function_arg_info
])
187 elif tag
== 'return':
188 if self
.in_function
== 1:
189 self
.function_return
= [self
.function_return_type
,
190 self
.function_return_info
,
191 self
.function_return_field
]
196 if self
.in_function
== 1:
197 self
.function_descr
= str
202 if self
.in_function
== 1:
203 self
.function_cond
= str
206 def function(name
, desc
, ret
, args
, file, module
, cond
):
208 if onlyOverrides
and name
not in functions
:
210 if name
== "virConnectListDomains":
211 name
= "virConnectListDomainsID"
212 functions
[name
] = (desc
, ret
, args
, file, module
, cond
)
214 def qemu_function(name
, desc
, ret
, args
, file, module
, cond
):
216 if onlyOverrides
and name
not in qemu_functions
:
218 qemu_functions
[name
] = (desc
, ret
, args
, file, module
, cond
)
220 def lxc_function(name
, desc
, ret
, args
, file, module
, cond
):
222 if onlyOverrides
and name
not in lxc_functions
:
224 lxc_functions
[name
] = (desc
, ret
, args
, file, module
, cond
)
226 def enum(type, name
, value
):
227 if type not in enums
:
229 if (name
.startswith('VIR_DOMAIN_EVENT_ID_') or
230 name
.startswith('VIR_NETWORK_EVENT_ID_')):
231 event_ids
.append(name
)
232 if value
== 'VIR_TYPED_PARAM_INT':
234 elif value
== 'VIR_TYPED_PARAM_UINT':
236 elif value
== 'VIR_TYPED_PARAM_LLONG':
238 elif value
== 'VIR_TYPED_PARAM_ULLONG':
240 elif value
== 'VIR_TYPED_PARAM_DOUBLE':
242 elif value
== 'VIR_TYPED_PARAM_BOOLEAN':
244 elif value
== 'VIR_DOMAIN_AFFECT_CURRENT':
246 elif value
== 'VIR_DOMAIN_AFFECT_LIVE':
248 elif value
== 'VIR_DOMAIN_AFFECT_CONFIG':
250 if onlyOverrides
and name
not in enums
[type]:
252 enums
[type][name
] = value
254 def lxc_enum(type, name
, value
):
255 if type not in lxc_enums
:
257 if onlyOverrides
and name
not in lxc_enums
[type]:
259 lxc_enums
[type][name
] = value
261 def qemu_enum(type, name
, value
):
262 if type not in qemu_enums
:
263 qemu_enums
[type] = {}
264 if onlyOverrides
and name
not in qemu_enums
[type]:
266 qemu_enums
[type][name
] = value
269 #######################################################################
271 # Some filtering rukes to drop functions/types which should not
272 # be exposed as-is on the Python interface
274 #######################################################################
276 functions_failed
= []
277 lxc_functions_failed
= []
278 qemu_functions_failed
= []
279 functions_skipped
= [
280 "virConnectListDomains",
282 lxc_functions_skipped
= []
283 qemu_functions_skipped
= []
289 # 'int *': "usually a return type",
290 'virConnectDomainEventCallback': "No function types in python",
291 'virConnectDomainEventGenericCallback': "No function types in python",
292 'virConnectDomainEventRTCChangeCallback': "No function types in python",
293 'virConnectDomainEventWatchdogCallback': "No function types in python",
294 'virConnectDomainEventIOErrorCallback': "No function types in python",
295 'virConnectDomainEventGraphicsCallback': "No function types in python",
296 'virConnectDomainQemuMonitorEventCallback': "No function types in python",
297 'virStreamEventCallback': "No function types in python",
298 'virEventHandleCallback': "No function types in python",
299 'virEventTimeoutCallback': "No function types in python",
300 'virDomainBlockJobInfoPtr': "Not implemented yet",
303 #######################################################################
305 # Table of remapping to/from the python type or class to the C
308 #######################################################################
311 'void': (None, None, None, None),
312 'int': ('i', None, "int", "int"),
313 'long': ('l', None, "long", "long"),
314 'double': ('d', None, "double", "double"),
315 'unsigned int': ('I', None, "int", "int"),
316 'unsigned long': ('l', None, "long", "long"),
317 'long long': ('L', None, "longlong", "long long"),
318 'unsigned long long': ('L', None, "longlong", "long long"),
319 'unsigned char *': ('z', None, "charPtr", "char *"),
320 'char *': ('z', None, "charPtr", "char *"),
321 'const char *': ('z', None, "constcharPtr", "const char *"),
322 'size_t': ('n', None, "size_t", "size_t"),
324 'virDomainPtr': ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
325 'virDomain *': ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
326 'const virDomain *': ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
328 'virNetworkPtr': ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
329 'virNetwork *': ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
330 'const virNetwork *': ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
332 'virInterfacePtr': ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),
333 'virInterface *': ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),
334 'const virInterface *': ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),
336 'virStoragePoolPtr': ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),
337 'virStoragePool *': ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),
338 'const virStoragePool *': ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),
340 'virStorageVolPtr': ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),
341 'virStorageVol *': ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),
342 'const virStorageVol *': ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),
344 'virConnectPtr': ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
345 'virConnect *': ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
346 'const virConnect *': ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
348 'virNodeDevicePtr': ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
349 'virNodeDevice *': ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
350 'const virNodeDevice *': ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
352 'virSecretPtr': ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
353 'virSecret *': ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
354 'const virSecret *': ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
356 'virNWFilterPtr': ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),
357 'virNWFilter *': ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),
358 'const virNWFilter *': ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),
360 'virNWFilterBindingPtr': ('O', "virNWFilterBinding", "virNWFilterBindingPtr", "virNWFilterBindingPtr"),
361 'virNWFilterBinding *': ('O', "virNWFilterBinding", "virNWFilterBindingPtr", "virNWFilterBindingPtr"),
362 'const virNWFilterBinding *': ('O', "virNWFilterBinding", "virNWFilterBindingPtr", "virNWFilterBindingPtr"),
364 'virStreamPtr': ('O', "virStream", "virStreamPtr", "virStreamPtr"),
365 'virStream *': ('O', "virStream", "virStreamPtr", "virStreamPtr"),
366 'const virStream *': ('O', "virStream", "virStreamPtr", "virStreamPtr"),
368 'virDomainCheckpointPtr': ('O', "virDomainCheckpoint", "virDomainCheckpointPtr", "virDomainCheckpointPtr"),
369 'virDomainCheckpoint *': ('O', "virDomainCheckpoint", "virDomainCheckpointPtr", "virDomainCheckpointPtr"),
370 'const virDomainCheckpoint *': ('O', "virDomainCheckpoint", "virDomainCheckpointPtr", "virDomainCheckpointPtr"),
372 'virDomainSnapshotPtr': ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
373 'virDomainSnapshot *': ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
374 'const virDomainSnapshot *': ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
379 #######################################################################
381 # This part writes the C <-> Python stubs libvirt.[ch] and
382 # the table libvirt-export.c to add when registrering the Python module
384 #######################################################################
386 # Class methods which are written by hand in libvirt.c but the Python-level
387 # code is still automatically generated (so they are not in skip_function()).
389 'virConnectGetVersion',
390 'virConnectGetLibVersion',
391 'virConnectListDomainsID',
392 'virConnectListDefinedDomains',
393 'virConnectListNetworks',
394 'virConnectListDefinedNetworks',
395 'virConnectListSecrets',
396 'virConnectListInterfaces',
397 'virConnectListStoragePools',
398 'virConnectListDefinedStoragePools',
399 'virConnectListStorageVols',
400 'virConnectListDefinedStorageVols',
401 'virConnectListDefinedInterfaces',
402 'virConnectListNWFilters',
403 'virDomainSnapshotListNames',
404 'virDomainSnapshotListChildrenNames',
405 'virConnGetLastError',
409 'virDomainGetControlInfo',
410 'virDomainGetBlockInfo',
411 'virDomainGetJobInfo',
412 'virDomainGetJobStats',
414 'virNodeGetSecurityModel',
415 'virDomainGetSecurityLabel',
416 'virDomainGetSecurityLabelList',
418 'virDomainGetUUIDString',
419 'virDomainLookupByUUID',
421 'virNetworkGetUUIDString',
422 'virNetworkLookupByUUID',
423 'virDomainGetAutostart',
424 'virNetworkGetAutostart',
425 'virDomainBlockStats',
426 'virDomainInterfaceStats',
427 'virDomainMemoryStats',
428 'virNodeGetCellsFreeMemory',
429 'virDomainGetSchedulerType',
430 'virDomainGetSchedulerParameters',
431 'virDomainGetSchedulerParametersFlags',
432 'virDomainSetSchedulerParameters',
433 'virDomainSetSchedulerParametersFlags',
434 'virDomainSetBlkioParameters',
435 'virDomainGetBlkioParameters',
436 'virDomainSetMemoryParameters',
437 'virDomainGetMemoryParameters',
438 'virDomainSetNumaParameters',
439 'virDomainGetNumaParameters',
442 'virDomainPinVcpuFlags',
443 'virDomainGetVcpuPinInfo',
444 'virDomainGetEmulatorPinInfo',
445 'virDomainPinEmulator',
446 'virDomainGetIOThreadInfo',
447 'virDomainPinIOThread',
448 'virDomainSetIOThreadParams',
452 'virSecretGetUUIDString',
453 'virSecretLookupByUUID',
454 'virNWFilterGetUUID',
455 'virNWFilterGetUUIDString',
456 'virNWFilterLookupByUUID',
457 'virStoragePoolGetUUID',
458 'virStoragePoolGetUUIDString',
459 'virStoragePoolLookupByUUID',
460 'virStoragePoolGetInfo',
461 'virStorageVolGetInfo',
462 'virStorageVolGetInfoFlags',
463 'virStoragePoolGetAutostart',
464 'virStoragePoolListVolumes',
465 'virDomainBlockPeek',
466 'virDomainMemoryPeek',
467 'virEventRegisterImpl',
468 'virNodeListDevices',
469 'virNodeDeviceListCaps',
470 'virConnectBaselineCPU',
471 'virDomainRevertToSnapshot',
473 'virNodeGetCPUStats',
474 'virNodeGetMemoryStats',
475 'virDomainGetBlockJobInfo',
476 'virDomainMigrateGetCompressionCache',
477 'virDomainMigrateGetMaxSpeed',
478 'virDomainMigrateGetMaxDowntime',
479 'virDomainBlockStatsFlags',
480 'virDomainSetBlockIoTune',
481 'virDomainGetBlockIoTune',
482 'virDomainSetInterfaceParameters',
483 'virDomainGetInterfaceParameters',
484 'virDomainGetCPUStats',
485 'virDomainGetDiskErrors',
486 'virNodeGetMemoryParameters',
487 'virNodeSetMemoryParameters',
490 'virDomainMigrateToURI3',
491 'virConnectGetCPUModelNames',
492 'virNodeGetFreePages',
493 'virNetworkGetDHCPLeases',
494 'virDomainBlockCopy',
496 'virDomainGetFSInfo',
497 'virDomainInterfaceAddresses',
498 'virDomainGetPerfEvents',
499 'virDomainSetPerfEvents',
500 'virDomainGetGuestVcpus',
501 'virConnectBaselineHypervisorCPU',
502 'virDomainGetLaunchSecurityInfo',
507 'virDomainLxcOpenNamespace',
511 'virDomainQemuMonitorCommand',
512 'virDomainQemuAgentCommand',
516 # These are functions which the generator skips completly - no python
517 # or C code is generated. Generally should not be used for any more
518 # functions than those already listed
520 'virConnectListDomains', # Python API is called virConectListDomainsID for unknown reasons
521 'virConnSetErrorFunc', # Not used in Python API XXX is this a bug ?
522 'virResetError', # Not used in Python API XXX is this a bug ?
523 'virGetVersion', # Python C code is manually written
524 'virSetErrorFunc', # Python API is called virRegisterErrorHandler for unknown reasons
525 'virConnCopyLastError', # Python API is called virConnGetLastError instead
526 'virCopyLastError', # Python API is called virGetLastError instead
527 'virConnectOpenAuth', # Python C code is manually written
528 'virDefaultErrorFunc', # Python virErrorFuncHandler impl calls this from C
529 'virConnectDomainEventRegister', # overridden in virConnect.py
530 'virConnectDomainEventDeregister', # overridden in virConnect.py
531 'virConnectDomainEventRegisterAny', # overridden in virConnect.py
532 'virConnectDomainEventDeregisterAny', # overridden in virConnect.py
533 'virConnectNetworkEventRegisterAny', # overridden in virConnect.py
534 'virConnectNetworkEventDeregisterAny', # overridden in virConnect.py
535 'virConnectStoragePoolEventRegisterAny', # overridden in virConnect.py
536 'virConnectStoragePoolEventDeregisterAny', # overridden in virConnect.py
537 'virConnectNodeDeviceEventRegisterAny', # overridden in virConnect.py
538 'virConnectNodeDeviceEventDeregisterAny', # overridden in virConnect.py
539 'virConnectSecretEventRegisterAny', # overridden in virConnect.py
540 'virConnectSecretEventDeregisterAny', # overridden in virConnect.py
541 'virSaveLastError', # We have our own python error wrapper
542 'virFreeError', # Only needed if we use virSaveLastError
543 'virConnectListAllDomains', # overridden in virConnect.py
544 'virDomainListAllCheckpoints', # overridden in virDomain.py
545 'virDomainCheckpointListAllChildren', # overridden in virDomainCheckpoint.py
546 'virDomainListAllSnapshots', # overridden in virDomain.py
547 'virDomainSnapshotListAllChildren', # overridden in virDomainSnapshot.py
548 'virConnectListAllStoragePools', # overridden in virConnect.py
549 'virStoragePoolListAllVolumes', # overridden in virStoragePool.py
550 'virConnectListAllNetworks', # 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.
588 "virNWFilterBindingRef",
592 "virDomainCheckpointRef",
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 "virSecretGetConnect",
602 "virNWFilterGetConnect",
603 "virStoragePoolGetConnect",
604 "virStorageVolGetConnect",
605 "virDomainCheckpointGetConnect",
606 "virDomainCheckpointGetDomain",
607 "virDomainSnapshotGetConnect",
608 "virDomainSnapshotGetDomain",
610 # only useful in C code, python code uses dict for typed parameters
611 "virTypedParamsAddBoolean",
612 "virTypedParamsAddDouble",
613 "virTypedParamsAddFromString",
614 "virTypedParamsAddInt",
615 "virTypedParamsAddLLong",
616 "virTypedParamsAddString",
617 "virTypedParamsAddUInt",
618 "virTypedParamsAddULLong",
619 "virTypedParamsClear",
620 "virTypedParamsFree",
622 "virTypedParamsGetBoolean",
623 "virTypedParamsGetDouble",
624 "virTypedParamsGetInt",
625 "virTypedParamsGetLLong",
626 "virTypedParamsGetString",
627 "virTypedParamsGetUInt",
628 "virTypedParamsGetULLong",
630 'virNetworkDHCPLeaseFree', # only useful in C, python code uses list
631 'virDomainStatsRecordListFree', # only useful in C, python uses dict
632 'virDomainFSInfoFree', # only useful in C, python code uses list
633 'virDomainIOThreadInfoFree', # only useful in C, python code uses list
634 'virDomainInterfaceFree', # only useful in C, python code uses list
637 lxc_skip_function
= (
638 "virDomainLxcEnterNamespace",
639 "virDomainLxcEnterSecurityLabel",
641 qemu_skip_function
= (
642 #"virDomainQemuAttach",
643 'virConnectDomainQemuMonitorEventRegister', # overridden in -qemu.py
644 'virConnectDomainQemuMonitorEventDeregister', # overridden in -qemu.py
647 # Generate C code, but skip python impl
648 function_skip_python_impl
= (
649 "virStreamFree", # Needed in custom virStream __del__, but free shouldn't
650 # be exposed in bindings
653 lxc_function_skip_python_impl
= ()
654 qemu_function_skip_python_impl
= ()
656 function_skip_index_one
= (
657 "virDomainRevertToSnapshot",
660 def print_function_wrapper(module
, name
, output
, export
, include
):
665 global qemu_functions
666 global skipped_modules
667 global function_skip_python_impl
670 if module
== "libvirt":
671 (desc
, ret
, args
, file, mod
, cond
) = functions
[name
]
672 if module
== "libvirt-lxc":
673 (desc
, ret
, args
, file, mod
, cond
) = lxc_functions
[name
]
674 if module
== "libvirt-qemu":
675 (desc
, ret
, args
, file, mod
, cond
) = qemu_functions
[name
]
677 print("failed to get function %s infos" % name
)
680 if module
in skipped_modules
:
683 if module
== "libvirt":
684 if name
in skip_function
:
686 if name
in skip_impl
:
687 # Don't delete the function entry in the caller.
689 elif module
== "libvirt-lxc":
690 if name
in lxc_skip_function
:
692 if name
in lxc_skip_impl
:
693 # Don't delete the function entry in the caller.
695 elif module
== "libvirt-qemu":
696 if name
in qemu_skip_function
:
698 if name
in qemu_skip_impl
:
699 # Don't delete the function entry in the caller.
710 # This should be correct
711 if arg
[1][0:6] == "const ":
713 c_args
= c_args
+ " %s %s;\n" % (arg
[1], arg
[0])
714 if arg
[1] in py_types
:
715 (f
, t
, n
, c
) = py_types
[arg
[1]]
719 format_args
= format_args
+ ", &pyobj_%s" % (arg
[0])
720 c_args
= c_args
+ " PyObject *pyobj_%s;\n" % (arg
[0])
721 c_convert
= c_convert
+ \
722 " %s = (%s) Py%s_Get(pyobj_%s);\n" % (arg
[0],
725 format_args
= format_args
+ ", &%s" % (arg
[0])
727 format_args
= format_args
+ ", &py_buffsize%d" % num_bufs
728 c_args
= c_args
+ " int py_buffsize%d;\n" % num_bufs
729 num_bufs
= num_bufs
+ 1
731 c_call
= c_call
+ ", "
732 c_call
= c_call
+ "%s" % (arg
[0])
734 if arg
[1] in skipped_types
:
736 if arg
[1] in unknown_types
:
737 lst
= unknown_types
[arg
[1]]
740 unknown_types
[arg
[1]] = [name
]
743 format
= format
+ ":%s" % (name
)
746 if file == "python_accessor":
747 if args
[1][1] == "char *":
748 c_call
= "\n VIR_FREE(%s->%s);\n" % (
749 args
[0][0], args
[1][0], args
[0][0], args
[1][0])
750 c_call
= c_call
+ " %s->%s = (%s)strdup((const xmlChar *)%s);\n" % (args
[0][0],
751 args
[1][0], args
[1][1], args
[1][0])
753 c_call
= "\n %s->%s = %s;\n" % (args
[0][0], args
[1][0],
756 c_call
= "\n %s(%s);\n" % (name
, c_call
)
757 ret_convert
= " Py_INCREF(Py_None);\n return Py_None;\n"
758 elif ret
[0] in py_types
:
759 (f
, t
, n
, c
) = py_types
[ret
[0]]
760 c_return
= " %s c_retval;\n" % (ret
[0])
761 if file == "python_accessor" and ret
[2] is not None:
762 c_call
= "\n c_retval = %s->%s;\n" % (args
[0][0], ret
[2])
764 c_call
= "\n c_retval = %s(%s);\n" % (name
, c_call
)
765 ret_convert
= " py_retval = libvirt_%sWrap((%s) c_retval);\n" % (n
,c
)
767 ret_convert
= ret_convert
+ " free(c_retval);\n"
768 ret_convert
= ret_convert
+ " return py_retval;\n"
770 if ret
[0] in skipped_types
:
772 if ret
[0] in unknown_types
:
773 lst
= unknown_types
[ret
[0]]
776 unknown_types
[ret
[0]] = [name
]
779 if cond
is not None and cond
!= "":
780 include
.write("#if %s\n" % cond
)
781 export
.write("#if %s\n" % cond
)
782 output
.write("#if %s\n" % cond
)
784 include
.write("PyObject * ")
785 if module
== "libvirt":
786 include
.write("libvirt_%s(PyObject *self, PyObject *args);\n" % (name
))
787 export
.write(" { (char *)\"%s\", libvirt_%s, METH_VARARGS, NULL },\n" %
789 elif module
== "libvirt-lxc":
790 include
.write("libvirt_lxc_%s(PyObject *self, PyObject *args);\n" % (name
))
791 export
.write(" { (char *)\"%s\", libvirt_lxc_%s, METH_VARARGS, NULL },\n" %
793 elif module
== "libvirt-qemu":
794 include
.write("libvirt_qemu_%s(PyObject *self, PyObject *args);\n" % (name
))
795 export
.write(" { (char *)\"%s\", libvirt_qemu_%s, METH_VARARGS, NULL },\n" %
799 # Those have been manually generated
800 if cond
is not None and cond
!= "":
801 include
.write("#endif\n")
802 export
.write("#endif\n")
803 output
.write("#endif\n")
805 if file == "python_accessor" and ret
[0] != "void" and ret
[2] is None:
806 # Those have been manually generated
807 if cond
is not None and cond
!= "":
808 include
.write("#endif\n")
809 export
.write("#endif\n")
810 output
.write("#endif\n")
813 output
.write("PyObject *\n")
814 if module
== "libvirt":
815 output
.write("libvirt_%s(PyObject *self ATTRIBUTE_UNUSED," % (name
))
816 elif module
== "libvirt-lxc":
817 output
.write("libvirt_lxc_%s(PyObject *self ATTRIBUTE_UNUSED," % (name
))
818 elif module
== "libvirt-qemu":
819 output
.write("libvirt_qemu_%s(PyObject *self ATTRIBUTE_UNUSED," % (name
))
820 output
.write(" PyObject *args")
822 output
.write(" ATTRIBUTE_UNUSED")
823 output
.write(") {\n")
825 output
.write(" PyObject *py_retval;\n")
827 output
.write(c_return
)
831 output
.write("\n if (!PyArg_ParseTuple(args, (char *)\"%s\"%s))\n" %
832 (format
, format_args
))
833 output
.write(" return NULL;\n")
835 output
.write(c_convert
+ "\n")
837 output
.write(" LIBVIRT_BEGIN_ALLOW_THREADS;")
839 output
.write(" LIBVIRT_END_ALLOW_THREADS;\n")
840 output
.write(ret_convert
)
841 output
.write("}\n\n")
842 if cond
is not None and cond
!= "":
843 include
.write("#endif /* %s */\n" % cond
)
844 export
.write("#endif /* %s */\n" % cond
)
845 output
.write("#endif /* %s */\n" % cond
)
847 if module
== "libvirt":
848 if name
in function_skip_python_impl
:
850 elif module
== "libvirt-lxc":
851 if name
in lxc_function_skip_python_impl
:
853 elif module
== "libvirt-qemu":
854 if name
in qemu_function_skip_python_impl
:
858 def print_c_pointer(classname
, output
, export
, include
):
859 output
.write("PyObject *\n")
860 output
.write("libvirt_%s_pointer(PyObject *self ATTRIBUTE_UNUSED, PyObject *args)\n" % classname
)
862 output
.write(" %sPtr ptr;\n" % classname
)
863 output
.write(" PyObject *pyptr;\n")
864 output
.write(" PyObject *pylong;\n")
866 output
.write(" if (!PyArg_ParseTuple(args, (char *) \"O\", &pyptr))\n")
867 output
.write(" return NULL;\n")
868 output
.write(" ptr = (%sPtr) Py%s_Get(pyptr);\n" % (classname
, classname
))
869 output
.write(" pylong = PyLong_FromVoidPtr(ptr);\n")
870 output
.write(" return pylong;\n")
874 include
.write("PyObject *libvirt_%s_pointer(PyObject *self, PyObject *args);\n" % classname
)
876 export
.write(" { (char *)\"%s_pointer\", libvirt_%s_pointer, METH_VARARGS, NULL },\n" %
877 (classname
, classname
))
879 def buildStubs(module
, api_xml
):
884 if module
not in ["libvirt", "libvirt-qemu", "libvirt-lxc"]:
885 print("ERROR: Unknown module type: %s" % module
)
888 if module
== "libvirt":
890 funcs_failed
= functions_failed
891 funcs_skipped
= functions_skipped
892 elif module
== "libvirt-lxc":
893 funcs
= lxc_functions
894 funcs_failed
= lxc_functions_failed
895 funcs_skipped
= lxc_functions_skipped
896 elif module
== "libvirt-qemu":
897 funcs
= qemu_functions
898 funcs_failed
= qemu_functions_failed
899 funcs_skipped
= qemu_functions_skipped
905 onlyOverrides
= False
906 (parser
, target
) = getparser()
910 msg
= sys
.exc_info()[1]
911 print(file, ":", msg
)
914 n
= len(list(funcs
.keys()))
916 print("Found %d functions in %s" % ((n
), api_xml
))
918 override_api_xml
= "%s-override-api.xml" % module
919 py_types
['pythonObject'] = ('O', "pythonObject", "pythonObject", "pythonObject")
922 f
= open(override_api_xml
)
926 (parser
, target
) = getparser()
930 msg
= sys
.exc_info()[1]
931 print(file, ":", msg
)
934 # XXX: This is not right, same function already in @functions
935 # will be overwritten.
936 print("Found %d functions in %s" % ((len(list(funcs
.keys())) - n
), override_api_xml
))
941 header_file
= "build/%s.h" % module
942 export_file
= "build/%s-export.c" % module
943 wrapper_file
= "build/%s.c" % module
945 include
= open(header_file
, "w")
946 include
.write("/* Generated by generator.py */\n\n")
948 export
= open(export_file
, "w")
949 export
.write("/* Generated by generator.py */\n\n")
951 wrapper
= open(wrapper_file
, "w")
952 wrapper
.write("/* Generated by generator.py */\n\n")
953 wrapper
.write("#include <Python.h>\n")
954 wrapper
.write("#include <libvirt/" + module
+ ".h>\n")
955 wrapper
.write("#include \"typewrappers.h\"\n")
956 wrapper
.write("#include \"build/" + module
+ ".h\"\n\n")
958 for function
in sorted(funcs
.keys()):
959 # Skip the functions which are not for the module
960 ret
= print_function_wrapper(module
, function
, wrapper
, export
, include
)
963 funcs_failed
.append(function
)
966 skipped
= skipped
+ 1
967 funcs_skipped
.append(function
)
970 nb_wrap
= nb_wrap
+ 1
972 if module
== "libvirt":
973 # Write C pointer conversion functions.
974 for classname
in primary_classes
:
975 print_c_pointer(classname
, wrapper
, export
, include
)
976 # Write define wrappers around event id enums, so that the
977 # preprocessor can see which enums were available.
978 for event_id
in event_ids
:
979 include
.write("#define %s %s\n" % (event_id
, event_id
))
986 print("Generated %d wrapper functions" % nb_wrap
)
989 print("Missing type converters: ")
990 for type in list(unknown_types
.keys()):
991 print("%s:%d " % (type, len(unknown_types
[type])))
993 for f
in funcs_failed
:
994 print("ERROR: failed %s" % f
)
998 if len(unknown_types
) > 0:
1002 #######################################################################
1004 # This part writes part of the Python front-end classes based on
1005 # mapping rules between types and classes and also based on function
1006 # renaming to get consistent function names at the Python level
1008 #######################################################################
1011 # The type automatically remapped to generated classes
1014 "virDomainPtr": ("._o", "virDomain(self,_obj=%s)", "virDomain"),
1015 "virDomain *": ("._o", "virDomain(self, _obj=%s)", "virDomain"),
1016 "virNetworkPtr": ("._o", "virNetwork(self, _obj=%s)", "virNetwork"),
1017 "virNetwork *": ("._o", "virNetwork(self, _obj=%s)", "virNetwork"),
1018 "virInterfacePtr": ("._o", "virInterface(self, _obj=%s)", "virInterface"),
1019 "virInterface *": ("._o", "virInterface(self, _obj=%s)", "virInterface"),
1020 "virStoragePoolPtr": ("._o", "virStoragePool(self, _obj=%s)", "virStoragePool"),
1021 "virStoragePool *": ("._o", "virStoragePool(self, _obj=%s)", "virStoragePool"),
1022 "virStorageVolPtr": ("._o", "virStorageVol(self, _obj=%s)", "virStorageVol"),
1023 "virStorageVol *": ("._o", "virStorageVol(self, _obj=%s)", "virStorageVol"),
1024 "virNodeDevicePtr": ("._o", "virNodeDevice(self, _obj=%s)", "virNodeDevice"),
1025 "virNodeDevice *": ("._o", "virNodeDevice(self, _obj=%s)", "virNodeDevice"),
1026 "virSecretPtr": ("._o", "virSecret(self, _obj=%s)", "virSecret"),
1027 "virSecret *": ("._o", "virSecret(self, _obj=%s)", "virSecret"),
1028 "virNWFilterPtr": ("._o", "virNWFilter(self, _obj=%s)", "virNWFilter"),
1029 "virNWFilter *": ("._o", "virNWFilter(self, _obj=%s)", "virNWFilter"),
1030 "virNWFilterBindingPtr": ("._o", "virNWFilterBinding(self, _obj=%s)", "virNWFilterBinding"),
1031 "virNWFilterBinding *": ("._o", "virNWFilterBinding(self, _obj=%s)", "virNWFilterBinding"),
1032 "virStreamPtr": ("._o", "virStream(self, _obj=%s)", "virStream"),
1033 "virStream *": ("._o", "virStream(self, _obj=%s)", "virStream"),
1034 "virConnectPtr": ("._o", "virConnect(_obj=%s)", "virConnect"),
1035 "virConnect *": ("._o", "virConnect(_obj=%s)", "virConnect"),
1036 "virDomainCheckpointPtr": ("._o", "virDomainCheckpoint(self,_obj=%s)", "virDomainCheckpoint"),
1037 "virDomainCheckpoint *": ("._o", "virDomainCheckpoint(self, _obj=%s)", "virDomainCheckpoint"),
1038 "virDomainSnapshotPtr": ("._o", "virDomainSnapshot(self,_obj=%s)", "virDomainSnapshot"),
1039 "virDomainSnapshot *": ("._o", "virDomainSnapshot(self, _obj=%s)", "virDomainSnapshot"),
1042 primary_classes
= ["virDomain", "virNetwork", "virInterface",
1043 "virStoragePool", "virStorageVol",
1044 "virConnect", "virNodeDevice", "virSecret",
1045 "virNWFilter", "virNWFilterBinding",
1046 "virStream", "virDomainCheckpoint", "virDomainSnapshot"]
1048 classes_destructors
= {
1049 "virDomain": "virDomainFree",
1050 "virNetwork": "virNetworkFree",
1051 "virInterface": "virInterfaceFree",
1052 "virStoragePool": "virStoragePoolFree",
1053 "virStorageVol": "virStorageVolFree",
1054 "virNodeDevice" : "virNodeDeviceFree",
1055 "virSecret": "virSecretFree",
1056 "virNWFilter": "virNWFilterFree",
1057 "virNWFilterBinding": "virNWFilterBindingFree",
1058 "virDomainCheckpoint": "virDomainCheckpointFree",
1059 "virDomainSnapshot": "virDomainSnapshotFree",
1060 # We hand-craft __del__ for this one
1061 #"virStream": "virStreamFree",
1064 class_skip_connect_impl
= {
1065 "virConnect" : True,
1068 class_domain_impl
= {
1069 "virDomainCheckpoint": True,
1070 "virDomainSnapshot": True,
1073 functions_noexcept
= {
1074 'virDomainGetID': True,
1075 'virDomainGetName': True,
1076 'virNetworkGetName': True,
1077 'virInterfaceGetName': True,
1078 'virStoragePoolGetName': True,
1079 'virStorageVolGetName': True,
1080 'virStorageVolGetkey': True,
1081 'virNodeDeviceGetName': True,
1082 'virNodeDeviceGetParent': True,
1083 'virSecretGetUsageType': True,
1084 'virSecretGetUsageID': True,
1085 'virNWFilterGetName': True,
1086 'virNWFilterBindingGetFilterName': True,
1087 'virNWFilterBindingGetPortDev': True,
1090 function_classes
= {}
1092 function_classes
["None"] = []
1094 # Functions returning an integral type which need special rules to
1095 # check for errors and raise exceptions.
1096 functions_int_exception_test
= {
1097 'virDomainGetMaxMemory': "%s == 0",
1099 functions_int_default_test
= "%s == -1"
1101 def is_integral_type (name
):
1102 return not re
.search ("^(unsigned)? ?(int|long)$", name
) is None
1104 def is_optional_arg(info
):
1105 return re
.search("^\(?optional\)?", info
) is not None
1107 def is_python_noninteger_type (name
):
1109 return name
[-1:] == "*"
1111 def nameFixup(name
, classe
, type, file):
1112 # avoid a disastrous clash
1113 listname
= classe
+ "List"
1116 if name
[0:l
] == listname
:
1118 func
= func
[0:1].lower() + func
[1:]
1119 elif name
[0:16] == "virNetworkDefine":
1121 func
= func
[0:1].lower() + func
[1:]
1122 elif name
[0:19] == "virNetworkCreateXML":
1124 func
= func
[0:1].lower() + func
[1:]
1125 elif name
[0:16] == "virNetworkLookup":
1127 func
= func
[0:1].lower() + func
[1:]
1128 elif name
[0:18] == "virInterfaceDefine":
1130 func
= func
[0:1].lower() + func
[1:]
1131 elif name
[0:21] == "virInterfaceCreateXML":
1133 func
= func
[0:1].lower() + func
[1:]
1134 elif name
[0:18] == "virInterfaceLookup":
1136 func
= func
[0:1].lower() + func
[1:]
1137 elif name
[0:15] == "virSecretDefine":
1139 func
= func
[0:1].lower() + func
[1:]
1140 elif name
[0:15] == "virSecretLookup":
1142 func
= func
[0:1].lower() + func
[1:]
1143 elif name
[0:27] == "virNWFilterBindingCreateXML":
1145 func
= func
[0:3].lower() + func
[3:]
1146 elif name
[0:24] == "virNWFilterBindingLookup":
1148 func
= func
[0:3].lower() + func
[3:]
1149 elif name
[0:24] == "virNWFilterBindingDefine":
1151 func
= func
[0:3].lower() + func
[3:]
1152 elif name
[0:24] == "virNWFilterBindingLookup":
1154 func
= func
[0:3].lower() + func
[3:]
1155 elif name
[0:17] == "virNWFilterDefine":
1157 func
= func
[0:3].lower() + func
[3:]
1158 elif name
[0:17] == "virNWFilterLookup":
1160 func
= func
[0:3].lower() + func
[3:]
1161 elif name
[0:20] == "virStoragePoolDefine":
1163 func
= func
[0:1].lower() + func
[1:]
1164 elif name
[0:23] == "virStoragePoolCreateXML":
1166 func
= func
[0:1].lower() + func
[1:]
1167 elif name
[0:20] == "virStoragePoolLookup":
1169 func
= func
[0:1].lower() + func
[1:]
1170 elif name
[0:19] == "virStorageVolDefine":
1172 func
= func
[0:1].lower() + func
[1:]
1173 elif name
[0:19] == "virStorageVolLookup":
1175 func
= func
[0:1].lower() + func
[1:]
1176 elif name
[0:20] == "virDomainGetCPUStats":
1178 func
= func
[0:1].lower() + func
[1:]
1179 elif name
[0:24] == "virDomainGetIOThreadInfo":
1181 func
= func
[0:2].lower() + func
[2:]
1182 elif name
[0:18] == "virDomainGetFSInfo":
1184 func
= func
[0:2].lower() + func
[2:]
1185 elif name
[0:12] == "virDomainGet":
1187 func
= func
[0:1].lower() + func
[1:]
1188 elif name
[0:31] == "virDomainCheckpointLookupByName":
1190 func
= func
[0:1].lower() + func
[1:]
1191 elif name
[0:28] == "virDomainCheckpointCreateXML":
1193 func
= func
[0:1].lower() + func
[1:]
1194 elif name
[0:26] == "virDomainCheckpointCurrent":
1196 func
= func
[0:1].lower() + func
[1:]
1197 elif name
[0:19] == "virDomainCheckpoint":
1199 func
= func
[0:1].lower() + func
[1:]
1200 elif name
[0:29] == "virDomainSnapshotLookupByName":
1202 func
= func
[0:1].lower() + func
[1:]
1203 elif name
[0:26] == "virDomainSnapshotListNames":
1205 func
= func
[0:1].lower() + func
[1:]
1206 elif name
[0:28] == "virDomainSnapshotNumChildren":
1208 func
= func
[0:1].lower() + func
[1:]
1209 elif name
[0:20] == "virDomainSnapshotNum":
1211 func
= func
[0:1].lower() + func
[1:]
1212 elif name
[0:27] == "virDomainSnapshotCreateXML2":
1214 func
= func
[0:1].lower() + func
[1:]
1215 elif name
[0:26] == "virDomainSnapshotCreateXML":
1217 func
= func
[0:1].lower() + func
[1:]
1218 elif name
[0:24] == "virDomainSnapshotCurrent":
1220 func
= func
[0:1].lower() + func
[1:]
1221 elif name
[0:17] == "virDomainSnapshot":
1223 func
= func
[0:1].lower() + func
[1:]
1224 elif name
[0:9] == "virDomain":
1226 func
= func
[0:1].lower() + func
[1:]
1227 elif name
[0:13] == "virNetworkGet":
1229 func
= func
[0:1].lower() + func
[1:]
1230 func
= func
.replace("dHCP", "DHCP")
1231 elif name
[0:10] == "virNetwork":
1233 func
= func
[0:1].lower() + func
[1:]
1234 elif name
[0:15] == "virInterfaceGet":
1236 func
= func
[0:1].lower() + func
[1:]
1237 elif name
[0:12] == "virInterface":
1239 func
= func
[0:1].lower() + func
[1:]
1240 elif name
[0:12] == 'virSecretGet':
1242 func
= func
[0:1].lower() + func
[1:]
1243 elif name
[0:9] == 'virSecret':
1245 func
= func
[0:1].lower() + func
[1:]
1246 elif name
[0:21] == 'virNWFilterBindingGet':
1248 func
= func
[0:1].lower() + func
[1:]
1249 elif name
[0:18] == 'virNWFilterBinding':
1251 func
= func
[0:1].lower() + func
[1:]
1252 elif name
[0:14] == 'virNWFilterGet':
1254 func
= func
[0:1].lower() + func
[1:]
1255 elif name
[0:11] == 'virNWFilter':
1257 func
= func
[0:1].lower() + func
[1:]
1258 elif name
[0:12] == 'virStreamNew':
1260 elif name
[0:9] == 'virStream':
1262 func
= func
[0:1].lower() + func
[1:]
1263 elif name
[0:17] == "virStoragePoolGet":
1265 func
= func
[0:1].lower() + func
[1:]
1266 elif name
[0:14] == "virStoragePool":
1268 func
= func
[0:1].lower() + func
[1:]
1269 elif name
[0:16] == "virStorageVolGet":
1271 func
= func
[0:1].lower() + func
[1:]
1272 elif name
[0:13] == "virStorageVol":
1274 func
= func
[0:1].lower() + func
[1:]
1275 elif name
[0:13] == "virNodeDevice":
1276 if name
[13:16] == "Get":
1277 func
= name
[16].lower() + name
[17:]
1278 elif name
[13:19] == "Lookup" or name
[13:19] == "Create":
1279 func
= name
[3].lower() + name
[4:]
1281 func
= name
[13].lower() + name
[14:]
1282 elif name
[0:7] == "virNode":
1284 func
= func
[0:1].lower() + func
[1:]
1285 elif name
[0:10] == "virConnect":
1287 func
= func
[0:1].lower() + func
[1:]
1288 elif name
[0:3] == "xml":
1290 func
= func
[0:1].lower() + func
[1:]
1297 if func
== "uUIDString":
1299 if func
== "oSType":
1301 if func
== "xMLDesc":
1303 if func
== "mACString":
1309 def functionSortKey(info
):
1310 (index
, func
, name
, ret
, args
, filename
, mod
) = info
1311 return func
, filename
1313 def writeDoc(module
, name
, args
, indent
, output
):
1314 if module
== "libvirt":
1316 elif module
== "libvirt-lxc":
1317 funcs
= lxc_functions
1318 elif module
== "libvirt-qemu":
1319 funcs
= qemu_functions
1320 if funcs
[name
][0] is None or funcs
[name
][0] == "":
1322 val
= funcs
[name
][0]
1323 val
= val
.replace("NULL", "None")
1324 output
.write(indent
)
1332 output
.write(indent
)
1334 output
.write(' """\n')
1336 def buildWrappers(module
):
1339 global unknown_types
1341 global function_classes
1344 global primary_classes
1345 global classes_destructors
1346 global functions_noexcept
1348 if not module
== "libvirt":
1349 print("ERROR: Unknown module type: %s" % module
)
1352 for type in list(classes_type
.keys()):
1353 function_classes
[classes_type
[type][2]] = []
1356 # Build the list of C types to look for ordered to start
1357 # with primary classes
1361 ctypes_processed
= {}
1362 classes_processed
= {}
1363 for classe
in primary_classes
:
1364 classes_list
.append(classe
)
1365 classes_processed
[classe
] = ()
1366 for type in list(classes_type
.keys()):
1367 tinfo
= classes_type
[type]
1368 if tinfo
[2] == classe
:
1370 ctypes_processed
[type] = ()
1371 for type in list(classes_type
.keys()):
1372 if type in ctypes_processed
:
1374 tinfo
= classes_type
[type]
1375 if tinfo
[2] not in classes_processed
:
1376 classes_list
.append(tinfo
[2])
1377 classes_processed
[tinfo
[2]] = ()
1380 ctypes_processed
[type] = ()
1382 for name
in list(functions
.keys()):
1384 (desc
, ret
, args
, file, mod
, cond
) = functions
[name
]
1386 classe
= classes_type
[type][2]
1388 if name
[0:3] == "vir" and len(args
) >= 1 and args
[0][1] == type:
1390 func
= nameFixup(name
, classe
, type, file)
1391 info
= (0, func
, name
, ret
, args
, file, mod
)
1392 function_classes
[classe
].append(info
)
1394 elif name
[0:3] == "vir" and len(args
) >= 2 and args
[1][1] == type \
1395 and file != "python_accessor" and not name
in function_skip_index_one
:
1397 func
= nameFixup(name
, classe
, type, file)
1398 info
= (1, func
, name
, ret
, args
, file, mod
)
1399 function_classes
[classe
].append(info
)
1403 func
= nameFixup(name
, "None", file, file)
1404 info
= (0, func
, name
, ret
, args
, file, mod
)
1405 function_classes
['None'].append(info
)
1407 classes_file
= "build/%s.py" % module
1408 extra_file
= "%s-override.py" % module
1411 classes
= open(classes_file
, "w")
1413 if os
.path
.exists(extra_file
):
1414 extra
= open(extra_file
, "r")
1415 classes
.write("#\n")
1416 classes
.write("# WARNING WARNING WARNING WARNING\n")
1417 classes
.write("#\n")
1418 classes
.write("# This file is automatically written by generator.py. Any changes\n")
1419 classes
.write("# made here will be lost.\n")
1420 classes
.write("#\n")
1421 classes
.write("# To change the manually written methods edit " + module
+ "-override.py\n")
1422 classes
.write("# To change the automatically written methods edit generator.py\n")
1423 classes
.write("#\n")
1424 classes
.write("# WARNING WARNING WARNING WARNING\n")
1425 classes
.write("#\n")
1426 if extra
is not None:
1427 classes
.writelines(extra
.readlines())
1428 classes
.write("#\n")
1429 classes
.write("# WARNING WARNING WARNING WARNING\n")
1430 classes
.write("#\n")
1431 classes
.write("# Automatically written part of python bindings for libvirt\n")
1432 classes
.write("#\n")
1433 classes
.write("# WARNING WARNING WARNING WARNING\n")
1434 if extra
is not None:
1437 if "None" in function_classes
:
1438 flist
= function_classes
["None"]
1439 flist
.sort(key
=functionSortKey
)
1442 (index
, func
, name
, ret
, args
, file, mod
) = info
1444 classes
.write("#\n# Functions from module %s\n#\n\n" % file)
1446 classes
.write("def %s(" % func
)
1451 classes
.write("%s" % arg
[0])
1452 if arg
[0] == "flags" or is_optional_arg(arg
[2]):
1453 if is_integral_type(arg
[1]):
1456 classes
.write("=None")
1458 classes
.write("):\n")
1459 writeDoc(module
, name
, args
, ' ', classes
)
1462 if arg
[1] in classes_type
:
1463 classes
.write(" if %s is None: %s__o = None\n" %
1465 classes
.write(" else: %s__o = %s%s\n" %
1466 (arg
[0], arg
[0], classes_type
[arg
[1]][0]))
1467 if ret
[0] != "void":
1468 classes
.write(" ret = ")
1471 classes
.write("libvirtmod.%s(" % name
)
1476 classes
.write("%s" % arg
[0])
1477 if arg
[1] in classes_type
:
1478 classes
.write("__o")
1480 classes
.write(")\n")
1482 if ret
[0] != "void":
1483 if ret
[0] in classes_type
:
1485 # Raise an exception
1487 if name
in functions_noexcept
:
1488 classes
.write(" if ret is None:return None\n")
1491 " if ret is None:raise libvirtError('%s() failed')\n" %
1494 classes
.write(" return ")
1495 classes
.write(classes_type
[ret
[0]][1] % ("ret"))
1498 # For functions returning an integral type there are
1499 # several things that we can do, depending on the
1500 # contents of functions_int_*:
1501 elif is_integral_type (ret
[0]):
1502 if name
not in functions_noexcept
:
1503 if name
in functions_int_exception_test
:
1504 test
= functions_int_exception_test
[name
]
1506 test
= functions_int_default_test
1507 classes
.write ((" if " + test
+
1508 ": raise libvirtError ('%s() failed')\n") %
1510 classes
.write(" return ret\n")
1512 elif is_python_noninteger_type (ret
[0]):
1513 if name
not in functions_noexcept
:
1514 classes
.write ((" if %s is None" +
1515 ": raise libvirtError ('%s() failed')\n") %
1517 classes
.write(" return ret\n")
1520 classes
.write(" return ret\n")
1524 for classname
in classes_list
:
1525 if classname
== "None":
1528 classes
.write("class %s(object):\n" % (classname
))
1529 if classname
in [ "virDomain", "virNetwork", "virInterface", "virStoragePool",
1530 "virStorageVol", "virNodeDevice", "virSecret","virStream",
1531 "virNWFilter", "virNWFilterBinding" ]:
1532 classes
.write(" def __init__(self, conn, _obj=None):\n")
1533 elif classname
in [ "virDomainCheckpoint", "virDomainSnapshot" ]:
1534 classes
.write(" def __init__(self, dom, _obj=None):\n")
1536 classes
.write(" def __init__(self, _obj=None):\n")
1537 if classname
in [ "virDomain", "virNetwork", "virInterface",
1538 "virNodeDevice", "virSecret", "virStream",
1539 "virNWFilter", "virNWFilterBinding" ]:
1540 classes
.write(" self._conn = conn\n")
1541 elif classname
in [ "virStorageVol", "virStoragePool" ]:
1542 classes
.write(" self._conn = conn\n" + \
1543 " if not isinstance(conn, virConnect):\n" + \
1544 " self._conn = conn._conn\n")
1545 elif classname
in [ "virDomainCheckpoint", "virDomainSnapshot" ]:
1546 classes
.write(" self._dom = dom\n")
1547 classes
.write(" self._conn = dom.connect()\n")
1548 classes
.write(" if type(_obj).__name__ not in [\"PyCapsule\", \"PyCObject\"]:\n")
1549 classes
.write(" raise Exception(\"Expected a wrapped C Object but got %s\" % type(_obj))\n")
1550 classes
.write(" self._o = _obj\n\n")
1552 if classname
in classes_destructors
:
1553 classes
.write(" def __del__(self):\n")
1554 classes
.write(" if self._o is not None:\n")
1555 classes
.write(" libvirtmod.%s(self._o)\n" %
1556 classes_destructors
[classname
])
1557 classes
.write(" self._o = None\n\n")
1558 destruct
=classes_destructors
[classname
]
1560 if classname
not in class_skip_connect_impl
:
1561 # Build python safe 'connect' method
1562 classes
.write(" def connect(self):\n")
1563 classes
.write(" return self._conn\n\n")
1565 if classname
in class_domain_impl
:
1566 classes
.write(" def domain(self):\n")
1567 classes
.write(" return self._dom\n\n")
1569 classes
.write(" def c_pointer(self):\n")
1570 classes
.write(" \"\"\"Get C pointer to underlying object\"\"\"\n")
1571 classes
.write(" return libvirtmod.%s_pointer(self._o)\n\n" %
1574 flist
= function_classes
[classname
]
1575 flist
.sort(key
=functionSortKey
)
1578 (index
, func
, name
, ret
, args
, file, mod
) = info
1580 # Do not provide as method the destructors for the class
1581 # to avoid double free
1583 if name
== destruct
:
1586 if file == "python_accessor":
1587 classes
.write(" # accessors for %s\n" % (classname
))
1589 classes
.write(" #\n")
1590 classes
.write(" # %s functions from module %s\n" % (
1592 classes
.write(" #\n\n")
1594 classes
.write(" def %s(self" % func
)
1598 classes
.write(", %s" % arg
[0])
1599 if arg
[0] == "flags" or is_optional_arg(arg
[2]):
1600 if is_integral_type(arg
[1]):
1603 classes
.write("=None")
1605 classes
.write("):\n")
1606 writeDoc(module
, name
, args
, ' ', classes
)
1609 if arg
[1] in classes_type
:
1611 classes
.write(" if %s is None: %s__o = None\n" %
1613 classes
.write(" else: %s__o = %s%s\n" %
1614 (arg
[0], arg
[0], classes_type
[arg
[1]][0]))
1616 if ret
[0] != "void":
1617 classes
.write(" ret = ")
1621 classes
.write("libvirtmod.%s(" % name
)
1626 classes
.write("%s" % arg
[0])
1627 if arg
[1] in classes_type
:
1628 classes
.write("__o")
1630 classes
.write("self")
1631 if arg
[1] in classes_type
:
1632 classes
.write(classes_type
[arg
[1]][0])
1634 classes
.write(")\n")
1636 if name
== "virConnectClose":
1637 classes
.write(" self._o = None\n")
1639 # For functions returning object types:
1640 if ret
[0] != "void":
1641 if ret
[0] in classes_type
:
1643 # Raise an exception
1645 if name
in functions_noexcept
:
1647 " if ret is None:return None\n")
1649 if classname
== "virConnect":
1651 " if ret is None:raise libvirtError('%s() failed', conn=self)\n" %
1653 elif classname
== "virDomain":
1655 " if ret is None:raise libvirtError('%s() failed', dom=self)\n" %
1657 elif classname
== "virNetwork":
1659 " if ret is None:raise libvirtError('%s() failed', net=self)\n" %
1661 elif classname
== "virInterface":
1663 " if ret is None:raise libvirtError('%s() failed', net=self)\n" %
1665 elif classname
== "virStoragePool":
1667 " if ret is None:raise libvirtError('%s() failed', pool=self)\n" %
1669 elif classname
== "virStorageVol":
1671 " if ret is None:raise libvirtError('%s() failed', vol=self)\n" %
1673 elif classname
in [ "virDomainCheckpoint", "virDomainSnapshot"]:
1675 " if ret is None:raise libvirtError('%s() failed', dom=self._dom)\n" %
1679 " if ret is None:raise libvirtError('%s() failed')\n" %
1683 # generate the returned class wrapper for the object
1685 classes
.write(" __tmp = ")
1686 classes
.write(classes_type
[ret
[0]][1] % ("ret"))
1692 classes
.write(" return __tmp\n")
1694 # For functions returning an integral type there
1695 # are several things that we can do, depending on
1696 # the contents of functions_int_*:
1697 elif is_integral_type (ret
[0]):
1698 if name
not in functions_noexcept
:
1699 if name
in functions_int_exception_test
:
1700 test
= functions_int_exception_test
[name
]
1702 test
= functions_int_default_test
1703 if classname
== "virConnect":
1704 classes
.write ((" if " + test
+
1705 ": raise libvirtError ('%s() failed', conn=self)\n") %
1707 elif classname
== "virDomain":
1708 classes
.write ((" if " + test
+
1709 ": raise libvirtError ('%s() failed', dom=self)\n") %
1711 elif classname
== "virNetwork":
1712 classes
.write ((" if " + test
+
1713 ": raise libvirtError ('%s() failed', net=self)\n") %
1715 elif classname
== "virInterface":
1716 classes
.write ((" if " + test
+
1717 ": raise libvirtError ('%s() failed', net=self)\n") %
1719 elif classname
== "virStoragePool":
1720 classes
.write ((" if " + test
+
1721 ": raise libvirtError ('%s() failed', pool=self)\n") %
1723 elif classname
== "virStorageVol":
1724 classes
.write ((" if " + test
+
1725 ": raise libvirtError ('%s() failed', vol=self)\n") %
1728 classes
.write ((" if " + test
+
1729 ": raise libvirtError ('%s() failed')\n") %
1732 classes
.write (" return ret\n")
1734 elif is_python_noninteger_type (ret
[0]):
1735 if name
not in functions_noexcept
:
1736 if classname
== "virConnect":
1737 classes
.write ((" if %s is None" +
1738 ": raise libvirtError ('%s() failed', conn=self)\n") %
1740 elif classname
== "virDomain":
1741 classes
.write ((" if %s is None" +
1742 ": raise libvirtError ('%s() failed', dom=self)\n") %
1744 elif classname
== "virNetwork":
1745 classes
.write ((" if %s is None" +
1746 ": raise libvirtError ('%s() failed', net=self)\n") %
1748 elif classname
== "virInterface":
1749 classes
.write ((" if %s is None" +
1750 ": raise libvirtError ('%s() failed', net=self)\n") %
1752 elif classname
== "virStoragePool":
1753 classes
.write ((" if %s is None" +
1754 ": raise libvirtError ('%s() failed', pool=self)\n") %
1756 elif classname
== "virStorageVol":
1757 classes
.write ((" if %s is None" +
1758 ": raise libvirtError ('%s() failed', vol=self)\n") %
1761 classes
.write ((" if %s is None" +
1762 ": raise libvirtError ('%s() failed')\n") %
1765 classes
.write (" return ret\n")
1767 classes
.write(" return ret\n")
1770 # Append "<classname>.py" to class def, iff it exists
1773 extra
= open("libvirt-override-" + classname
+ ".py", "r")
1774 classes
.write (" #\n")
1775 classes
.write (" # %s methods from %s.py (hand coded)\n" % (classname
,classname
))
1776 classes
.write (" #\n")
1780 # Since we compile with older libvirt, we don't want to pull
1781 # in manually written python methods which call C methods
1782 # that don't exist. This code attempts to detect which
1783 # methods to skip by looking at the libvirtmod.XXXX calls
1785 def shouldSkip(lines
):
1787 offset
= line
.find("libvirtmod.")
1789 func
= line
[offset
+ 11:]
1790 offset
= func
.find("(")
1791 func
= func
[0:offset
]
1792 if func
not in functions_skipped
:
1796 for line
in extra
.readlines():
1797 offset
= line
.find(" def ")
1799 name
= line
[offset
+5:]
1800 offset
= name
.find("(")
1801 name
= name
[0:offset
]
1802 if cached
is not None:
1803 if not shouldSkip(cached
):
1804 classes
.writelines(cached
)
1805 if name
== "__del__":
1811 if cached
is not None:
1815 if not shouldSkip(cached
):
1816 classes
.writelines(cached
)
1823 # Generate enum constants
1825 def enumsSortKey(data
):
1830 value
= float('inf')
1831 return value
, data
[0]
1833 # Resolve only one level of reference
1834 def resolveEnum(enum
, data
):
1835 for name
,val
in enum
.items():
1839 enum
[name
] = data
[val
]
1842 enumvals
= list(enums
.items())
1843 # convert list of dicts to one dict
1845 for type,enum
in enumvals
:
1846 enumData
.update(enum
)
1848 if enumvals
is not None:
1849 enumvals
.sort(key
=lambda x
: x
[0])
1850 for type,enum
in enumvals
:
1851 classes
.write("# %s\n" % type)
1852 items
= list(resolveEnum(enum
, enumData
).items())
1853 items
.sort(key
=enumsSortKey
)
1854 if items
[-1][0].endswith('_LAST'):
1856 for name
,value
in items
:
1857 classes
.write("%s = %s\n" % (name
,value
))
1860 classes
.write("# typed parameter names\n")
1861 for name
, value
in params
:
1862 classes
.write("%s = \"%s\"\n" % (name
, value
))
1866 def qemuBuildWrappers(module
):
1867 global qemu_functions
1869 if not module
== "libvirt-qemu":
1870 print("ERROR: only libvirt-qemu is supported")
1873 extra_file
= "%s-override.py" % module
1876 fd
= open("build/libvirt_qemu.py", "w")
1878 if os
.path
.exists(extra_file
):
1879 extra
= open(extra_file
, "r")
1881 fd
.write("# WARNING WARNING WARNING WARNING\n")
1883 fd
.write("# This file is automatically written by generator.py. Any changes\n")
1884 fd
.write("# made here will be lost.\n")
1886 fd
.write("# To change the manually written methods edit " + module
+ "-override.py\n")
1887 fd
.write("# To change the automatically written methods edit generator.py\n")
1889 fd
.write("# WARNING WARNING WARNING WARNING\n")
1891 fd
.write("# Automatically written part of python bindings for libvirt\n")
1894 fd
.write("import sys\n")
1897 fd
.write(" import libvirtmod_qemu\n")
1898 fd
.write("except ImportError:\n")
1899 fd
.write(" lib_e = sys.exc_info()[1]\n")
1901 fd
.write(" import cygvirtmod_qemu as libvirtmod_qemu\n")
1902 fd
.write(" except ImportError:\n")
1903 fd
.write(" cyg_e = sys.exc_info()[1]\n")
1904 fd
.write(" if str(cyg_e).count(\"No module named\"):\n")
1905 fd
.write(" raise lib_e\n\n")
1907 fd
.write("import libvirt\n\n")
1908 fd
.write("# WARNING WARNING WARNING WARNING\n")
1910 if extra
is not None:
1911 fd
.writelines(extra
.readlines())
1913 if extra
is not None:
1916 fd
.write("# WARNING WARNING WARNING WARNING\n")
1918 fd
.write("#\n# Functions from module %s\n#\n\n" % module
)
1920 # Generate functions directly, no classes
1922 for name
in sorted(qemu_functions
.keys()):
1923 func
= nameFixup(name
, 'None', None, None)
1924 (desc
, ret
, args
, file, mod
, cond
) = qemu_functions
[name
]
1925 fd
.write("def %s(" % func
)
1930 fd
.write("%s" % arg
[0])
1933 writeDoc(module
, name
, args
, ' ', fd
)
1935 if ret
[0] != "void":
1939 fd
.write("libvirtmod_qemu.%s(" % name
)
1945 if arg
[1] == "virConnectPtr":
1950 if arg
[1] in ["virDomainPtr", "virConnectPtr"]:
1951 # FIXME: This might have problem if the function
1952 # has multiple args which are objects.
1953 fd
.write("%s.%s" % (arg
[0], "_o"))
1955 fd
.write("%s" % arg
[0])
1959 if ret
[0] != "void":
1960 fd
.write(" if ret is None: raise libvirt.libvirtError('" + name
+ "() failed')\n")
1961 if ret
[0] == "virDomainPtr":
1962 fd
.write(" __tmp = libvirt.virDomain(" + conn
+ ", _obj=ret)\n")
1963 fd
.write(" return __tmp\n")
1965 fd
.write(" return ret\n")
1970 # Generate enum constants
1972 for type,enum
in sorted(qemu_enums
.items()):
1973 fd
.write("# %s\n" % type)
1974 items
= list(enum
.items())
1975 items
.sort(key
=lambda i
: (int(i
[1]), i
[0]))
1976 for name
,value
in items
:
1977 fd
.write("%s = %s\n" % (name
,value
))
1983 def lxcBuildWrappers(module
):
1984 global lxc_functions
1986 if not module
== "libvirt-lxc":
1987 print("ERROR: only libvirt-lxc is supported")
1990 extra_file
= "%s-override.py" % module
1993 fd
= open("build/libvirt_lxc.py", "w")
1995 if os
.path
.exists(extra_file
):
1996 extra
= open(extra_file
, "r")
1998 fd
.write("# WARNING WARNING WARNING WARNING\n")
2000 fd
.write("# This file is automatically written by generator.py. Any changes\n")
2001 fd
.write("# made here will be lost.\n")
2003 fd
.write("# To change the manually written methods edit " + module
+ "-override.py\n")
2004 fd
.write("# To change the automatically written methods edit generator.py\n")
2006 fd
.write("# WARNING WARNING WARNING WARNING\n")
2008 if extra
is not None:
2009 fd
.writelines(extra
.readlines())
2011 fd
.write("# WARNING WARNING WARNING WARNING\n")
2013 fd
.write("# Automatically written part of python bindings for libvirt\n")
2015 fd
.write("# WARNING WARNING WARNING WARNING\n")
2016 if extra
is not None:
2019 fd
.write("import sys\n")
2022 fd
.write(" import libvirtmod_lxc\n")
2023 fd
.write("except ImportError:\n")
2024 fd
.write(" lib_e = sys.exc_info()[1]\n")
2026 fd
.write(" import cygvirtmod_lxc as libvirtmod_lxc\n")
2027 fd
.write(" except ImportError:\n")
2028 fd
.write(" cyg_e = sys.exc_info()[1]\n")
2029 fd
.write(" if str(cyg_e).count(\"No module named\"):\n")
2030 fd
.write(" raise lib_e\n\n")
2032 fd
.write("import libvirt\n\n")
2033 fd
.write("#\n# Functions from module %s\n#\n\n" % module
)
2035 # Generate functions directly, no classes
2037 for name
in sorted(lxc_functions
.keys()):
2038 func
= nameFixup(name
, 'None', None, None)
2039 (desc
, ret
, args
, file, mod
, cond
) = lxc_functions
[name
]
2040 fd
.write("def %s(" % func
)
2045 fd
.write("%s" % arg
[0])
2048 writeDoc(module
, name
, args
, ' ', fd
)
2050 if ret
[0] != "void":
2054 fd
.write("libvirtmod_lxc.%s(" % name
)
2060 if arg
[1] == "virConnectPtr":
2065 if arg
[1] in ["virDomainPtr", "virConnectPtr"]:
2066 # FIXME: This might have problem if the function
2067 # has multiple args which are objects.
2068 fd
.write("%s.%s" % (arg
[0], "_o"))
2070 fd
.write("%s" % arg
[0])
2074 if ret
[0] != "void":
2075 fd
.write(" if ret is None: raise libvirt.libvirtError('" + name
+ "() failed')\n")
2076 if ret
[0] == "virDomainPtr":
2077 fd
.write(" __tmp = libvirt.virDomain(" + conn
+ ", _obj=ret)\n")
2078 fd
.write(" return __tmp\n")
2080 fd
.write(" return ret\n")
2085 # Generate enum constants
2087 for type,enum
in sorted(lxc_enums
.items()):
2088 fd
.write("# %s\n" % type)
2089 items
= list(enum
.items())
2090 items
.sort(key
=lambda i
: (int(i
[1]), i
[0]))
2091 for name
,value
in items
:
2092 fd
.write("%s = %s\n" % (name
,value
))
2099 if not os
.path
.exists("build"):
2102 if buildStubs(sys
.argv
[1], sys
.argv
[2]) < 0:
2105 if sys
.argv
[1] == "libvirt":
2106 buildWrappers(sys
.argv
[1])
2107 elif sys
.argv
[1] == "libvirt-lxc":
2108 lxcBuildWrappers(sys
.argv
[1])
2109 elif sys
.argv
[1] == "libvirt-qemu":
2110 qemuBuildWrappers(sys
.argv
[1])
2112 print("ERROR: unknown module %s" % sys
.argv
[1])