Add virDomainCheckpoint APIs
[libvirt-python/ericb.git] / generator.py
bloba16f9b1f0cd2f582cd210f01e39881b93fff68dd
1 #!/usr/bin/env python
3 # generate python wrappers from the XML API description
6 functions = {}
7 lxc_functions = {}
8 qemu_functions = {}
9 enums = {} # { enumType: { enumConstant: enumValue } }
10 lxc_enums = {} # { enumType: { enumConstant: enumValue } }
11 qemu_enums = {} # { enumType: { enumConstant: enumValue } }
12 event_ids = []
13 params = [] # [ (parameName, paramValue)... ]
15 import os
16 import sys
17 import string
18 import re
20 quiet=True
22 #######################################################################
24 # That part if purely the API acquisition phase from the
25 # libvirt API description
27 #######################################################################
28 import os
29 import xml.sax
31 debug = 0
32 onlyOverrides = False
34 libvirt_headers = [
35 "libvirt",
36 "libvirt-common",
37 "libvirt-domain",
38 "libvirt-domain-checkpoint",
39 "libvirt-domain-snapshot",
40 "libvirt-event",
41 "libvirt-host",
42 "libvirt-interface",
43 "libvirt-network",
44 "libvirt-nodedev",
45 "libvirt-nwfilter",
46 "libvirt-secret",
47 "libvirt-storage",
48 "libvirt-stream",
51 def getparser():
52 # Attach parser to an unmarshalling object. return both objects.
53 target = docParser()
54 parser = xml.sax.make_parser()
55 parser.setContentHandler(target)
56 return parser, target
58 class docParser(xml.sax.handler.ContentHandler):
59 def __init__(self):
60 self._methodname = None
61 self._data = []
62 self.in_function = 0
64 self.startElement = self.start
65 self.endElement = self.end
66 self.characters = self.data
68 def close(self):
69 if debug:
70 print("close")
72 def getmethodname(self):
73 return self._methodname
75 def data(self, text):
76 if debug:
77 print("data %s" % text)
78 self._data.append(text)
80 def cdata(self, text):
81 if debug:
82 print("data %s" % text)
83 self._data.append(text)
85 def start(self, tag, attrs):
86 if debug:
87 print("start %s, %s" % (tag, attrs))
88 if tag == 'function':
89 self._data = []
90 self.in_function = 1
91 self.function = None
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']
104 elif tag == 'cond':
105 self._data = []
106 elif tag == 'info':
107 self._data = []
108 elif tag == 'arg':
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']
132 elif tag == 'enum':
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'])
140 elif tag == "macro":
141 if "string" in attrs.keys():
142 params.append((attrs['name'], attrs['string']))
144 def end(self, tag):
145 if debug:
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,
155 self.function_cond)
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,
160 self.function_cond)
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,
165 self.function_cond)
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,
170 self.function_cond)
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,
175 self.function_cond)
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,
180 self.function_cond)
181 self.in_function = 0
182 elif tag == 'arg':
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]
192 elif tag == 'info':
193 str = ''
194 for c in self._data:
195 str = str + c
196 if self.in_function == 1:
197 self.function_descr = str
198 elif tag == 'cond':
199 str = ''
200 for c in self._data:
201 str = str + c
202 if self.in_function == 1:
203 self.function_cond = str
206 def function(name, desc, ret, args, file, module, cond):
207 global onlyOverrides
208 if onlyOverrides and name not in functions:
209 return
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):
215 global onlyOverrides
216 if onlyOverrides and name not in qemu_functions:
217 return
218 qemu_functions[name] = (desc, ret, args, file, module, cond)
220 def lxc_function(name, desc, ret, args, file, module, cond):
221 global onlyOverrides
222 if onlyOverrides and name not in lxc_functions:
223 return
224 lxc_functions[name] = (desc, ret, args, file, module, cond)
226 def enum(type, name, value):
227 if type not in enums:
228 enums[type] = {}
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':
233 value = 1
234 elif value == 'VIR_TYPED_PARAM_UINT':
235 value = 2
236 elif value == 'VIR_TYPED_PARAM_LLONG':
237 value = 3
238 elif value == 'VIR_TYPED_PARAM_ULLONG':
239 value = 4
240 elif value == 'VIR_TYPED_PARAM_DOUBLE':
241 value = 5
242 elif value == 'VIR_TYPED_PARAM_BOOLEAN':
243 value = 6
244 elif value == 'VIR_DOMAIN_AFFECT_CURRENT':
245 value = 0
246 elif value == 'VIR_DOMAIN_AFFECT_LIVE':
247 value = 1
248 elif value == 'VIR_DOMAIN_AFFECT_CONFIG':
249 value = 2
250 if onlyOverrides and name not in enums[type]:
251 return
252 enums[type][name] = value
254 def lxc_enum(type, name, value):
255 if type not in lxc_enums:
256 lxc_enums[type] = {}
257 if onlyOverrides and name not in lxc_enums[type]:
258 return
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]:
265 return
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 = []
285 skipped_modules = {
288 skipped_types = {
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
306 # counterpart.
308 #######################################################################
310 py_types = {
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"),
377 unknown_types = {}
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()).
388 skip_impl = (
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',
406 'virGetLastError',
407 'virDomainGetInfo',
408 'virDomainGetState',
409 'virDomainGetControlInfo',
410 'virDomainGetBlockInfo',
411 'virDomainGetJobInfo',
412 'virDomainGetJobStats',
413 'virNodeGetInfo',
414 'virNodeGetSecurityModel',
415 'virDomainGetSecurityLabel',
416 'virDomainGetSecurityLabelList',
417 'virDomainGetUUID',
418 'virDomainGetUUIDString',
419 'virDomainLookupByUUID',
420 'virNetworkGetUUID',
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',
440 'virDomainGetVcpus',
441 'virDomainPinVcpu',
442 'virDomainPinVcpuFlags',
443 'virDomainGetVcpuPinInfo',
444 'virDomainGetEmulatorPinInfo',
445 'virDomainPinEmulator',
446 'virDomainGetIOThreadInfo',
447 'virDomainPinIOThread',
448 'virDomainSetIOThreadParams',
449 'virSecretGetValue',
450 'virSecretSetValue',
451 'virSecretGetUUID',
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',
472 'virDomainSendKey',
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',
488 'virNodeGetCPUMap',
489 'virDomainMigrate3',
490 'virDomainMigrateToURI3',
491 'virConnectGetCPUModelNames',
492 'virNodeGetFreePages',
493 'virNetworkGetDHCPLeases',
494 'virDomainBlockCopy',
495 'virNodeAllocPages',
496 'virDomainGetFSInfo',
497 'virDomainInterfaceAddresses',
498 'virDomainGetPerfEvents',
499 'virDomainSetPerfEvents',
500 'virDomainGetGuestVcpus',
501 'virConnectBaselineHypervisorCPU',
502 'virDomainGetLaunchSecurityInfo',
503 'virNodeGetSEVInfo',
506 lxc_skip_impl = (
507 'virDomainLxcOpenNamespace',
510 qemu_skip_impl = (
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
519 skip_function = (
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.
581 "virConnectRef",
582 "virDomainRef",
583 "virInterfaceRef",
584 "virNetworkRef",
585 "virNodeDeviceRef",
586 "virSecretRef",
587 "virNWFilterRef",
588 "virNWFilterBindingRef",
589 "virStoragePoolRef",
590 "virStorageVolRef",
591 "virStreamRef",
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",
621 "virTypedParamsGet",
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):
661 global py_types
662 global unknown_types
663 global functions
664 global lxc_functions
665 global qemu_functions
666 global skipped_modules
667 global function_skip_python_impl
669 try:
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]
676 except:
677 print("failed to get function %s infos" % name)
678 return
680 if module in skipped_modules:
681 return 0
683 if module == "libvirt":
684 if name in skip_function:
685 return 0
686 if name in skip_impl:
687 # Don't delete the function entry in the caller.
688 return 1
689 elif module == "libvirt-lxc":
690 if name in lxc_skip_function:
691 return 0
692 if name in lxc_skip_impl:
693 # Don't delete the function entry in the caller.
694 return 1
695 elif module == "libvirt-qemu":
696 if name in qemu_skip_function:
697 return 0
698 if name in qemu_skip_impl:
699 # Don't delete the function entry in the caller.
700 return 1
702 c_call = ""
703 format=""
704 format_args=""
705 c_args=""
706 c_return=""
707 c_convert=""
708 num_bufs=0
709 for arg in args:
710 # This should be correct
711 if arg[1][0:6] == "const ":
712 arg[1] = arg[1][6:]
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]]
716 if f is not None:
717 format = format + f
718 if t is not None:
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],
723 arg[1], t, arg[0])
724 else:
725 format_args = format_args + ", &%s" % (arg[0])
726 if f == 't#':
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
730 if c_call != "":
731 c_call = c_call + ", "
732 c_call = c_call + "%s" % (arg[0])
733 else:
734 if arg[1] in skipped_types:
735 return 0
736 if arg[1] in unknown_types:
737 lst = unknown_types[arg[1]]
738 lst.append(name)
739 else:
740 unknown_types[arg[1]] = [name]
741 return -1
742 if format != "":
743 format = format + ":%s" % (name)
745 if ret[0] == 'void':
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])
752 else:
753 c_call = "\n %s->%s = %s;\n" % (args[0][0], args[1][0],
754 args[1][0])
755 else:
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])
763 else:
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)
766 if n == "charPtr":
767 ret_convert = ret_convert + " free(c_retval);\n"
768 ret_convert = ret_convert + " return py_retval;\n"
769 else:
770 if ret[0] in skipped_types:
771 return 0
772 if ret[0] in unknown_types:
773 lst = unknown_types[ret[0]]
774 lst.append(name)
775 else:
776 unknown_types[ret[0]] = [name]
777 return -1
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" %
788 (name, name))
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" %
792 (name, name))
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" %
796 (name, name))
798 if file == "python":
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")
804 return 1
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")
811 return 1
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")
821 if format == "":
822 output.write(" ATTRIBUTE_UNUSED")
823 output.write(") {\n")
824 if ret[0] != 'void':
825 output.write(" PyObject *py_retval;\n")
826 if c_return != "":
827 output.write(c_return)
828 if c_args != "":
829 output.write(c_args)
830 if format != "":
831 output.write("\n if (!PyArg_ParseTuple(args, (char *)\"%s\"%s))\n" %
832 (format, format_args))
833 output.write(" return NULL;\n")
834 if c_convert != "":
835 output.write(c_convert + "\n")
837 output.write(" LIBVIRT_BEGIN_ALLOW_THREADS;")
838 output.write(c_call)
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:
849 return 0
850 elif module == "libvirt-lxc":
851 if name in lxc_function_skip_python_impl:
852 return 0
853 elif module == "libvirt-qemu":
854 if name in qemu_function_skip_python_impl:
855 return 0
856 return 1
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)
861 output.write("{\n")
862 output.write(" %sPtr ptr;\n" % classname)
863 output.write(" PyObject *pyptr;\n")
864 output.write(" PyObject *pylong;\n")
865 output.write("\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")
871 output.write("}\n")
872 output.write("\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):
880 global py_types
881 global unknown_types
882 global onlyOverrides
884 if module not in ["libvirt", "libvirt-qemu", "libvirt-lxc"]:
885 print("ERROR: Unknown module type: %s" % module)
886 return None
888 if module == "libvirt":
889 funcs = functions
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
901 try:
902 f = open(api_xml)
903 data = f.read()
904 f.close()
905 onlyOverrides = False
906 (parser, target) = getparser()
907 parser.feed(data)
908 parser.close()
909 except IOError:
910 msg = sys.exc_info()[1]
911 print(file, ":", msg)
912 sys.exit(1)
914 n = len(list(funcs.keys()))
915 if not quiet:
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")
921 try:
922 f = open(override_api_xml)
923 data = f.read()
924 f.close()
925 onlyOverrides = True
926 (parser, target) = getparser()
927 parser.feed(data)
928 parser.close()
929 except IOError:
930 msg = sys.exc_info()[1]
931 print(file, ":", msg)
933 if not quiet:
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))
937 nb_wrap = 0
938 failed = 0
939 skipped = 0
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)
961 if ret < 0:
962 failed = failed + 1
963 funcs_failed.append(function)
964 del funcs[function]
965 if ret == 0:
966 skipped = skipped + 1
967 funcs_skipped.append(function)
968 del funcs[function]
969 if ret == 1:
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))
981 include.close()
982 export.close()
983 wrapper.close()
985 if not quiet:
986 print("Generated %d wrapper functions" % nb_wrap)
988 if unknown_types:
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)
996 if failed > 0:
997 return -1
998 if len(unknown_types) > 0:
999 return -1
1000 return 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
1013 classes_type = {
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"
1114 ll = len(listname)
1115 l = len(classe)
1116 if name[0:l] == listname:
1117 func = name[l:]
1118 func = func[0:1].lower() + func[1:]
1119 elif name[0:16] == "virNetworkDefine":
1120 func = name[3:]
1121 func = func[0:1].lower() + func[1:]
1122 elif name[0:19] == "virNetworkCreateXML":
1123 func = name[3:]
1124 func = func[0:1].lower() + func[1:]
1125 elif name[0:16] == "virNetworkLookup":
1126 func = name[3:]
1127 func = func[0:1].lower() + func[1:]
1128 elif name[0:18] == "virInterfaceDefine":
1129 func = name[3:]
1130 func = func[0:1].lower() + func[1:]
1131 elif name[0:21] == "virInterfaceCreateXML":
1132 func = name[3:]
1133 func = func[0:1].lower() + func[1:]
1134 elif name[0:18] == "virInterfaceLookup":
1135 func = name[3:]
1136 func = func[0:1].lower() + func[1:]
1137 elif name[0:15] == "virSecretDefine":
1138 func = name[3:]
1139 func = func[0:1].lower() + func[1:]
1140 elif name[0:15] == "virSecretLookup":
1141 func = name[3:]
1142 func = func[0:1].lower() + func[1:]
1143 elif name[0:27] == "virNWFilterBindingCreateXML":
1144 func = name[3:]
1145 func = func[0:3].lower() + func[3:]
1146 elif name[0:24] == "virNWFilterBindingLookup":
1147 func = name[3:]
1148 func = func[0:3].lower() + func[3:]
1149 elif name[0:24] == "virNWFilterBindingDefine":
1150 func = name[3:]
1151 func = func[0:3].lower() + func[3:]
1152 elif name[0:24] == "virNWFilterBindingLookup":
1153 func = name[3:]
1154 func = func[0:3].lower() + func[3:]
1155 elif name[0:17] == "virNWFilterDefine":
1156 func = name[3:]
1157 func = func[0:3].lower() + func[3:]
1158 elif name[0:17] == "virNWFilterLookup":
1159 func = name[3:]
1160 func = func[0:3].lower() + func[3:]
1161 elif name[0:20] == "virStoragePoolDefine":
1162 func = name[3:]
1163 func = func[0:1].lower() + func[1:]
1164 elif name[0:23] == "virStoragePoolCreateXML":
1165 func = name[3:]
1166 func = func[0:1].lower() + func[1:]
1167 elif name[0:20] == "virStoragePoolLookup":
1168 func = name[3:]
1169 func = func[0:1].lower() + func[1:]
1170 elif name[0:19] == "virStorageVolDefine":
1171 func = name[3:]
1172 func = func[0:1].lower() + func[1:]
1173 elif name[0:19] == "virStorageVolLookup":
1174 func = name[3:]
1175 func = func[0:1].lower() + func[1:]
1176 elif name[0:20] == "virDomainGetCPUStats":
1177 func = name[9:]
1178 func = func[0:1].lower() + func[1:]
1179 elif name[0:24] == "virDomainGetIOThreadInfo":
1180 func = name[12:]
1181 func = func[0:2].lower() + func[2:]
1182 elif name[0:18] == "virDomainGetFSInfo":
1183 func = name[12:]
1184 func = func[0:2].lower() + func[2:]
1185 elif name[0:12] == "virDomainGet":
1186 func = name[12:]
1187 func = func[0:1].lower() + func[1:]
1188 elif name[0:31] == "virDomainCheckpointLookupByName":
1189 func = name[9:]
1190 func = func[0:1].lower() + func[1:]
1191 elif name[0:28] == "virDomainCheckpointCreateXML":
1192 func = name[9:]
1193 func = func[0:1].lower() + func[1:]
1194 elif name[0:26] == "virDomainCheckpointCurrent":
1195 func = name[9:]
1196 func = func[0:1].lower() + func[1:]
1197 elif name[0:19] == "virDomainCheckpoint":
1198 func = name[19:]
1199 func = func[0:1].lower() + func[1:]
1200 elif name[0:29] == "virDomainSnapshotLookupByName":
1201 func = name[9:]
1202 func = func[0:1].lower() + func[1:]
1203 elif name[0:26] == "virDomainSnapshotListNames":
1204 func = name[9:]
1205 func = func[0:1].lower() + func[1:]
1206 elif name[0:28] == "virDomainSnapshotNumChildren":
1207 func = name[17:]
1208 func = func[0:1].lower() + func[1:]
1209 elif name[0:20] == "virDomainSnapshotNum":
1210 func = name[9:]
1211 func = func[0:1].lower() + func[1:]
1212 elif name[0:27] == "virDomainSnapshotCreateXML2":
1213 func = name[9:]
1214 func = func[0:1].lower() + func[1:]
1215 elif name[0:26] == "virDomainSnapshotCreateXML":
1216 func = name[9:]
1217 func = func[0:1].lower() + func[1:]
1218 elif name[0:24] == "virDomainSnapshotCurrent":
1219 func = name[9:]
1220 func = func[0:1].lower() + func[1:]
1221 elif name[0:17] == "virDomainSnapshot":
1222 func = name[17:]
1223 func = func[0:1].lower() + func[1:]
1224 elif name[0:9] == "virDomain":
1225 func = name[9:]
1226 func = func[0:1].lower() + func[1:]
1227 elif name[0:13] == "virNetworkGet":
1228 func = name[13:]
1229 func = func[0:1].lower() + func[1:]
1230 func = func.replace("dHCP", "DHCP")
1231 elif name[0:10] == "virNetwork":
1232 func = name[10:]
1233 func = func[0:1].lower() + func[1:]
1234 elif name[0:15] == "virInterfaceGet":
1235 func = name[15:]
1236 func = func[0:1].lower() + func[1:]
1237 elif name[0:12] == "virInterface":
1238 func = name[12:]
1239 func = func[0:1].lower() + func[1:]
1240 elif name[0:12] == 'virSecretGet':
1241 func = name[12:]
1242 func = func[0:1].lower() + func[1:]
1243 elif name[0:9] == 'virSecret':
1244 func = name[9:]
1245 func = func[0:1].lower() + func[1:]
1246 elif name[0:21] == 'virNWFilterBindingGet':
1247 func = name[21:]
1248 func = func[0:1].lower() + func[1:]
1249 elif name[0:18] == 'virNWFilterBinding':
1250 func = name[18:]
1251 func = func[0:1].lower() + func[1:]
1252 elif name[0:14] == 'virNWFilterGet':
1253 func = name[14:]
1254 func = func[0:1].lower() + func[1:]
1255 elif name[0:11] == 'virNWFilter':
1256 func = name[11:]
1257 func = func[0:1].lower() + func[1:]
1258 elif name[0:12] == 'virStreamNew':
1259 func = "newStream"
1260 elif name[0:9] == 'virStream':
1261 func = name[9:]
1262 func = func[0:1].lower() + func[1:]
1263 elif name[0:17] == "virStoragePoolGet":
1264 func = name[17:]
1265 func = func[0:1].lower() + func[1:]
1266 elif name[0:14] == "virStoragePool":
1267 func = name[14:]
1268 func = func[0:1].lower() + func[1:]
1269 elif name[0:16] == "virStorageVolGet":
1270 func = name[16:]
1271 func = func[0:1].lower() + func[1:]
1272 elif name[0:13] == "virStorageVol":
1273 func = name[13:]
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:]
1280 else:
1281 func = name[13].lower() + name[14:]
1282 elif name[0:7] == "virNode":
1283 func = name[7:]
1284 func = func[0:1].lower() + func[1:]
1285 elif name[0:10] == "virConnect":
1286 func = name[10:]
1287 func = func[0:1].lower() + func[1:]
1288 elif name[0:3] == "xml":
1289 func = name[3:]
1290 func = func[0:1].lower() + func[1:]
1291 else:
1292 func = name
1293 if func == "iD":
1294 func = "ID"
1295 if func == "uUID":
1296 func = "UUID"
1297 if func == "uUIDString":
1298 func = "UUIDString"
1299 if func == "oSType":
1300 func = "OSType"
1301 if func == "xMLDesc":
1302 func = "XMLDesc"
1303 if func == "mACString":
1304 func = "MACString"
1306 return func
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":
1315 funcs = functions
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] == "":
1321 return
1322 val = funcs[name][0]
1323 val = val.replace("NULL", "None")
1324 output.write(indent)
1325 output.write('"""')
1326 i = val.find("\n")
1327 while i >= 0:
1328 str = val[0:i+1]
1329 val = val[i+1:]
1330 output.write(str)
1331 i = val.find("\n")
1332 output.write(indent)
1333 output.write(val)
1334 output.write(' """\n')
1336 def buildWrappers(module):
1337 global ctypes
1338 global py_types
1339 global unknown_types
1340 global functions
1341 global function_classes
1342 global classes_type
1343 global classes_list
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)
1350 return None
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
1359 ctypes = []
1360 classes_list = []
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:
1369 ctypes.append(type)
1370 ctypes_processed[type] = ()
1371 for type in list(classes_type.keys()):
1372 if type in ctypes_processed:
1373 continue
1374 tinfo = classes_type[type]
1375 if tinfo[2] not in classes_processed:
1376 classes_list.append(tinfo[2])
1377 classes_processed[tinfo[2]] = ()
1379 ctypes.append(type)
1380 ctypes_processed[type] = ()
1382 for name in list(functions.keys()):
1383 found = 0
1384 (desc, ret, args, file, mod, cond) = functions[name]
1385 for type in ctypes:
1386 classe = classes_type[type][2]
1388 if name[0:3] == "vir" and len(args) >= 1 and args[0][1] == type:
1389 found = 1
1390 func = nameFixup(name, classe, type, file)
1391 info = (0, func, name, ret, args, file, mod)
1392 function_classes[classe].append(info)
1393 break
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:
1396 found = 1
1397 func = nameFixup(name, classe, type, file)
1398 info = (1, func, name, ret, args, file, mod)
1399 function_classes[classe].append(info)
1400 break
1401 if found == 1:
1402 continue
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
1409 extra = None
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:
1435 extra.close()
1437 if "None" in function_classes:
1438 flist = function_classes["None"]
1439 flist.sort(key=functionSortKey)
1440 oldfile = ""
1441 for info in flist:
1442 (index, func, name, ret, args, file, mod) = info
1443 if file != oldfile:
1444 classes.write("#\n# Functions from module %s\n#\n\n" % file)
1445 oldfile = file
1446 classes.write("def %s(" % func)
1447 n = 0
1448 for arg in args:
1449 if n != 0:
1450 classes.write(", ")
1451 classes.write("%s" % arg[0])
1452 if arg[0] == "flags" or is_optional_arg(arg[2]):
1453 if is_integral_type(arg[1]):
1454 classes.write("=0")
1455 else:
1456 classes.write("=None")
1457 n = n + 1
1458 classes.write("):\n")
1459 writeDoc(module, name, args, ' ', classes)
1461 for arg in args:
1462 if arg[1] in classes_type:
1463 classes.write(" if %s is None: %s__o = None\n" %
1464 (arg[0], arg[0]))
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 = ")
1469 else:
1470 classes.write(" ")
1471 classes.write("libvirtmod.%s(" % name)
1472 n = 0
1473 for arg in args:
1474 if n != 0:
1475 classes.write(", ")
1476 classes.write("%s" % arg[0])
1477 if arg[1] in classes_type:
1478 classes.write("__o")
1479 n = n + 1
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")
1489 else:
1490 classes.write(
1491 " if ret is None:raise libvirtError('%s() failed')\n" %
1492 (name))
1494 classes.write(" return ")
1495 classes.write(classes_type[ret[0]][1] % ("ret"))
1496 classes.write("\n")
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]
1505 else:
1506 test = functions_int_default_test
1507 classes.write ((" if " + test +
1508 ": raise libvirtError ('%s() failed')\n") %
1509 ("ret", name))
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") %
1516 ("ret", name))
1517 classes.write(" return ret\n")
1519 else:
1520 classes.write(" return ret\n")
1522 classes.write("\n")
1524 for classname in classes_list:
1525 if classname == "None":
1526 pass
1527 else:
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")
1535 else:
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")
1551 destruct=None
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" %
1572 classname)
1574 flist = function_classes[classname]
1575 flist.sort(key=functionSortKey)
1576 oldfile = ""
1577 for info in flist:
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:
1584 continue
1585 if file != oldfile:
1586 if file == "python_accessor":
1587 classes.write(" # accessors for %s\n" % (classname))
1588 else:
1589 classes.write(" #\n")
1590 classes.write(" # %s functions from module %s\n" % (
1591 classname, file))
1592 classes.write(" #\n\n")
1593 oldfile = file
1594 classes.write(" def %s(self" % func)
1595 n = 0
1596 for arg in args:
1597 if n != index:
1598 classes.write(", %s" % arg[0])
1599 if arg[0] == "flags" or is_optional_arg(arg[2]):
1600 if is_integral_type(arg[1]):
1601 classes.write("=0")
1602 else:
1603 classes.write("=None")
1604 n = n + 1
1605 classes.write("):\n")
1606 writeDoc(module, name, args, ' ', classes)
1607 n = 0
1608 for arg in args:
1609 if arg[1] in classes_type:
1610 if n != index:
1611 classes.write(" if %s is None: %s__o = None\n" %
1612 (arg[0], arg[0]))
1613 classes.write(" else: %s__o = %s%s\n" %
1614 (arg[0], arg[0], classes_type[arg[1]][0]))
1615 n = n + 1
1616 if ret[0] != "void":
1617 classes.write(" ret = ")
1618 else:
1619 classes.write(" ")
1620 n = 0
1621 classes.write("libvirtmod.%s(" % name)
1622 for arg in args:
1623 if n != 0:
1624 classes.write(", ")
1625 if n != index:
1626 classes.write("%s" % arg[0])
1627 if arg[1] in classes_type:
1628 classes.write("__o")
1629 else:
1630 classes.write("self")
1631 if arg[1] in classes_type:
1632 classes.write(classes_type[arg[1]][0])
1633 n = n + 1
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:
1646 classes.write(
1647 " if ret is None:return None\n")
1648 else:
1649 if classname == "virConnect":
1650 classes.write(
1651 " if ret is None:raise libvirtError('%s() failed', conn=self)\n" %
1652 (name))
1653 elif classname == "virDomain":
1654 classes.write(
1655 " if ret is None:raise libvirtError('%s() failed', dom=self)\n" %
1656 (name))
1657 elif classname == "virNetwork":
1658 classes.write(
1659 " if ret is None:raise libvirtError('%s() failed', net=self)\n" %
1660 (name))
1661 elif classname == "virInterface":
1662 classes.write(
1663 " if ret is None:raise libvirtError('%s() failed', net=self)\n" %
1664 (name))
1665 elif classname == "virStoragePool":
1666 classes.write(
1667 " if ret is None:raise libvirtError('%s() failed', pool=self)\n" %
1668 (name))
1669 elif classname == "virStorageVol":
1670 classes.write(
1671 " if ret is None:raise libvirtError('%s() failed', vol=self)\n" %
1672 (name))
1673 elif classname in [ "virDomainCheckpoint", "virDomainSnapshot"]:
1674 classes.write(
1675 " if ret is None:raise libvirtError('%s() failed', dom=self._dom)\n" %
1676 (name))
1677 else:
1678 classes.write(
1679 " if ret is None:raise libvirtError('%s() failed')\n" %
1680 (name))
1683 # generate the returned class wrapper for the object
1685 classes.write(" __tmp = ")
1686 classes.write(classes_type[ret[0]][1] % ("ret"))
1687 classes.write("\n")
1690 # return the class
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]
1701 else:
1702 test = functions_int_default_test
1703 if classname == "virConnect":
1704 classes.write ((" if " + test +
1705 ": raise libvirtError ('%s() failed', conn=self)\n") %
1706 ("ret", name))
1707 elif classname == "virDomain":
1708 classes.write ((" if " + test +
1709 ": raise libvirtError ('%s() failed', dom=self)\n") %
1710 ("ret", name))
1711 elif classname == "virNetwork":
1712 classes.write ((" if " + test +
1713 ": raise libvirtError ('%s() failed', net=self)\n") %
1714 ("ret", name))
1715 elif classname == "virInterface":
1716 classes.write ((" if " + test +
1717 ": raise libvirtError ('%s() failed', net=self)\n") %
1718 ("ret", name))
1719 elif classname == "virStoragePool":
1720 classes.write ((" if " + test +
1721 ": raise libvirtError ('%s() failed', pool=self)\n") %
1722 ("ret", name))
1723 elif classname == "virStorageVol":
1724 classes.write ((" if " + test +
1725 ": raise libvirtError ('%s() failed', vol=self)\n") %
1726 ("ret", name))
1727 else:
1728 classes.write ((" if " + test +
1729 ": raise libvirtError ('%s() failed')\n") %
1730 ("ret", name))
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") %
1739 ("ret", name))
1740 elif classname == "virDomain":
1741 classes.write ((" if %s is None" +
1742 ": raise libvirtError ('%s() failed', dom=self)\n") %
1743 ("ret", name))
1744 elif classname == "virNetwork":
1745 classes.write ((" if %s is None" +
1746 ": raise libvirtError ('%s() failed', net=self)\n") %
1747 ("ret", name))
1748 elif classname == "virInterface":
1749 classes.write ((" if %s is None" +
1750 ": raise libvirtError ('%s() failed', net=self)\n") %
1751 ("ret", name))
1752 elif classname == "virStoragePool":
1753 classes.write ((" if %s is None" +
1754 ": raise libvirtError ('%s() failed', pool=self)\n") %
1755 ("ret", name))
1756 elif classname == "virStorageVol":
1757 classes.write ((" if %s is None" +
1758 ": raise libvirtError ('%s() failed', vol=self)\n") %
1759 ("ret", name))
1760 else:
1761 classes.write ((" if %s is None" +
1762 ": raise libvirtError ('%s() failed')\n") %
1763 ("ret", name))
1765 classes.write (" return ret\n")
1766 else:
1767 classes.write(" return ret\n")
1769 classes.write("\n")
1770 # Append "<classname>.py" to class def, iff it exists
1771 try:
1772 wantfuncs = []
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")
1777 cached = None
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):
1786 for line in lines:
1787 offset = line.find("libvirtmod.")
1788 if offset != -1:
1789 func = line[offset + 11:]
1790 offset = func.find("(")
1791 func = func[0:offset]
1792 if func not in functions_skipped:
1793 return True
1794 return False
1796 for line in extra.readlines():
1797 offset = line.find(" def ")
1798 if offset != -1:
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__":
1806 cached = None
1807 classes.write(line)
1808 else:
1809 cached = [line]
1810 else:
1811 if cached is not None:
1812 cached.append(line)
1813 else:
1814 classes.write(line)
1815 if not shouldSkip(cached):
1816 classes.writelines(cached)
1817 classes.write("\n")
1818 extra.close()
1819 except:
1820 pass
1823 # Generate enum constants
1825 def enumsSortKey(data):
1826 value = data[1]
1827 try:
1828 value = int(value)
1829 except ValueError:
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():
1836 try:
1837 int(val)
1838 except ValueError:
1839 enum[name] = data[val]
1840 return enum
1842 enumvals = list(enums.items())
1843 # convert list of dicts to one dict
1844 enumData = {}
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'):
1855 del items[-1]
1856 for name,value in items:
1857 classes.write("%s = %s\n" % (name,value))
1858 classes.write("\n")
1860 classes.write("# typed parameter names\n")
1861 for name, value in params:
1862 classes.write("%s = \"%s\"\n" % (name, value))
1864 classes.close()
1866 def qemuBuildWrappers(module):
1867 global qemu_functions
1869 if not module == "libvirt-qemu":
1870 print("ERROR: only libvirt-qemu is supported")
1871 return None
1873 extra_file = "%s-override.py" % module
1874 extra = None
1876 fd = open("build/libvirt_qemu.py", "w")
1878 if os.path.exists(extra_file):
1879 extra = open(extra_file, "r")
1880 fd.write("#\n")
1881 fd.write("# WARNING WARNING WARNING WARNING\n")
1882 fd.write("#\n")
1883 fd.write("# This file is automatically written by generator.py. Any changes\n")
1884 fd.write("# made here will be lost.\n")
1885 fd.write("#\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")
1888 fd.write("#\n")
1889 fd.write("# WARNING WARNING WARNING WARNING\n")
1890 fd.write("#\n")
1891 fd.write("# Automatically written part of python bindings for libvirt\n")
1892 fd.write("#\n")
1894 fd.write("import sys\n")
1896 fd.write("try:\n")
1897 fd.write(" import libvirtmod_qemu\n")
1898 fd.write("except ImportError:\n")
1899 fd.write(" lib_e = sys.exc_info()[1]\n")
1900 fd.write(" try:\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")
1909 fd.write("#\n")
1910 if extra is not None:
1911 fd.writelines(extra.readlines())
1912 fd.write("#\n")
1913 if extra is not None:
1914 extra.close()
1916 fd.write("# WARNING WARNING WARNING WARNING\n")
1917 fd.write("#\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)
1926 n = 0
1927 for arg in args:
1928 if n != 0:
1929 fd.write(", ")
1930 fd.write("%s" % arg[0])
1931 n = n + 1
1932 fd.write("):\n")
1933 writeDoc(module, name, args, ' ', fd)
1935 if ret[0] != "void":
1936 fd.write(" ret = ")
1937 else:
1938 fd.write(" ")
1939 fd.write("libvirtmod_qemu.%s(" % name)
1940 n = 0
1942 conn = None
1944 for arg in args:
1945 if arg[1] == "virConnectPtr":
1946 conn = arg[0]
1948 if n != 0:
1949 fd.write(", ")
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"))
1954 else:
1955 fd.write("%s" % arg[0])
1956 n = n + 1
1957 fd.write(")\n")
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")
1964 else:
1965 fd.write(" return ret\n")
1967 fd.write("\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))
1978 fd.write("\n")
1980 fd.close()
1983 def lxcBuildWrappers(module):
1984 global lxc_functions
1986 if not module == "libvirt-lxc":
1987 print("ERROR: only libvirt-lxc is supported")
1988 return None
1990 extra_file = "%s-override.py" % module
1991 extra = None
1993 fd = open("build/libvirt_lxc.py", "w")
1995 if os.path.exists(extra_file):
1996 extra = open(extra_file, "r")
1997 fd.write("#\n")
1998 fd.write("# WARNING WARNING WARNING WARNING\n")
1999 fd.write("#\n")
2000 fd.write("# This file is automatically written by generator.py. Any changes\n")
2001 fd.write("# made here will be lost.\n")
2002 fd.write("#\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")
2005 fd.write("#\n")
2006 fd.write("# WARNING WARNING WARNING WARNING\n")
2007 fd.write("#\n")
2008 if extra is not None:
2009 fd.writelines(extra.readlines())
2010 fd.write("#\n")
2011 fd.write("# WARNING WARNING WARNING WARNING\n")
2012 fd.write("#\n")
2013 fd.write("# Automatically written part of python bindings for libvirt\n")
2014 fd.write("#\n")
2015 fd.write("# WARNING WARNING WARNING WARNING\n")
2016 if extra is not None:
2017 extra.close()
2019 fd.write("import sys\n")
2021 fd.write("try:\n")
2022 fd.write(" import libvirtmod_lxc\n")
2023 fd.write("except ImportError:\n")
2024 fd.write(" lib_e = sys.exc_info()[1]\n")
2025 fd.write(" try:\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)
2041 n = 0
2042 for arg in args:
2043 if n != 0:
2044 fd.write(", ")
2045 fd.write("%s" % arg[0])
2046 n = n + 1
2047 fd.write("):\n")
2048 writeDoc(module, name, args, ' ', fd)
2050 if ret[0] != "void":
2051 fd.write(" ret = ")
2052 else:
2053 fd.write(" ")
2054 fd.write("libvirtmod_lxc.%s(" % name)
2055 n = 0
2057 conn = None
2059 for arg in args:
2060 if arg[1] == "virConnectPtr":
2061 conn = arg[0]
2063 if n != 0:
2064 fd.write(", ")
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"))
2069 else:
2070 fd.write("%s" % arg[0])
2071 n = n + 1
2072 fd.write(")\n")
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")
2079 else:
2080 fd.write(" return ret\n")
2082 fd.write("\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))
2093 fd.write("\n")
2095 fd.close()
2098 quiet = 0
2099 if not os.path.exists("build"):
2100 os.mkdir("build")
2102 if buildStubs(sys.argv[1], sys.argv[2]) < 0:
2103 sys.exit(1)
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])
2111 else:
2112 print("ERROR: unknown module %s" % sys.argv[1])
2113 sys.exit(1)
2115 sys.exit(0)