generator.py 68.4 KB
Newer Older
1 2 3 4 5 6
#!/usr/bin/python -u
#
# generate python wrappers from the XML API description
#

functions = {}
7
qemu_functions = {}
8
enums = {} # { enumType: { enumConstant: enumValue } }
9
qemu_enums = {} # { enumType: { enumConstant: enumValue } }
10 11 12 13

import os
import sys
import string
14
import re
15

16 17
quiet=True

18 19 20
if __name__ == "__main__":
    # launched as a script
    srcPref = os.path.dirname(sys.argv[0])
21 22 23 24 25
    if len(sys.argv) > 1:
        python = sys.argv[1]
    else:
        print "Python binary not specified"
        sys.exit(1)
26 27 28 29 30 31 32
else:
    # imported
    srcPref = os.path.dirname(__file__)

#######################################################################
#
#  That part if purely the API acquisition phase from the
33
#  libvirt API description
34 35 36
#
#######################################################################
import os
37
import xml.sax
38 39 40

debug = 0

41 42 43
def getparser():
    # Attach parser to an unmarshalling object. return both objects.
    target = docParser()
44 45 46
    parser = xml.sax.make_parser()
    parser.setContentHandler(target)
    return parser, target
47

48
class docParser(xml.sax.handler.ContentHandler):
49 50 51 52 53
    def __init__(self):
        self._methodname = None
        self._data = []
        self.in_function = 0

54 55 56 57
        self.startElement = self.start
        self.endElement = self.end
        self.characters = self.data

58 59 60 61 62 63 64 65 66 67 68 69
    def close(self):
        if debug:
            print "close"

    def getmethodname(self):
        return self._methodname

    def data(self, text):
        if debug:
            print "data %s" % text
        self._data.append(text)

70 71 72 73 74
    def cdata(self, text):
        if debug:
            print "data %s" % text
        self._data.append(text)

75 76 77 78 79 80 81 82 83 84 85 86
    def start(self, tag, attrs):
        if debug:
            print "start %s, %s" % (tag, attrs)
        if tag == 'function':
            self._data = []
            self.in_function = 1
            self.function = None
            self.function_cond = None
            self.function_args = []
            self.function_descr = None
            self.function_return = None
            self.function_file = None
87
            self.function_module= None
88 89 90 91
            if attrs.has_key('name'):
                self.function = attrs['name']
            if attrs.has_key('file'):
                self.function_file = attrs['file']
92 93
            if attrs.has_key('module'):
                self.function_module= attrs['module']
94 95 96 97 98 99 100 101 102 103 104
        elif tag == 'cond':
            self._data = []
        elif tag == 'info':
            self._data = []
        elif tag == 'arg':
            if self.in_function == 1:
                self.function_arg_name = None
                self.function_arg_type = None
                self.function_arg_info = None
                if attrs.has_key('name'):
                    self.function_arg_name = attrs['name']
105 106
                    if self.function_arg_name == 'from':
                        self.function_arg_name = 'frm'
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
                if attrs.has_key('type'):
                    self.function_arg_type = attrs['type']
                if attrs.has_key('info'):
                    self.function_arg_info = attrs['info']
        elif tag == 'return':
            if self.in_function == 1:
                self.function_return_type = None
                self.function_return_info = None
                self.function_return_field = None
                if attrs.has_key('type'):
                    self.function_return_type = attrs['type']
                if attrs.has_key('info'):
                    self.function_return_info = attrs['info']
                if attrs.has_key('field'):
                    self.function_return_field = attrs['field']
        elif tag == 'enum':
123 124
            if (attrs['file'] == "libvirt" or
                attrs['file'] == "virterror"):
125 126 127
                enum(attrs['type'],attrs['name'],attrs['value'])
            elif attrs['file'] == "libvirt-qemu":
                qemu_enum(attrs['type'],attrs['name'],attrs['value'])
128 129 130 131 132 133

    def end(self, tag):
        if debug:
            print "end %s" % tag
        if tag == 'function':
            if self.function != None:
134 135 136
                if (self.function_module == "libvirt" or
                    self.function_module == "event" or
                    self.function_module == "virterror"):
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
                    function(self.function, self.function_descr,
                             self.function_return, self.function_args,
                             self.function_file, self.function_module,
                             self.function_cond)
                elif self.function_module == "libvirt-qemu":
                    qemu_function(self.function, self.function_descr,
                             self.function_return, self.function_args,
                             self.function_file, self.function_module,
                             self.function_cond)
                elif self.function_file == "python":
                    function(self.function, self.function_descr,
                             self.function_return, self.function_args,
                             self.function_file, self.function_module,
                             self.function_cond)
                elif self.function_file == "python-qemu":
                    qemu_function(self.function, self.function_descr,
                                  self.function_return, self.function_args,
                                  self.function_file, self.function_module,
                                  self.function_cond)
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
                self.in_function = 0
        elif tag == 'arg':
            if self.in_function == 1:
                self.function_args.append([self.function_arg_name,
                                           self.function_arg_type,
                                           self.function_arg_info])
        elif tag == 'return':
            if self.in_function == 1:
                self.function_return = [self.function_return_type,
                                        self.function_return_info,
                                        self.function_return_field]
        elif tag == 'info':
            str = ''
            for c in self._data:
                str = str + c
            if self.in_function == 1:
                self.function_descr = str
        elif tag == 'cond':
            str = ''
            for c in self._data:
                str = str + c
            if self.in_function == 1:
                self.function_cond = str
179 180


181 182 183 184 185
def function(name, desc, ret, args, file, module, cond):
    functions[name] = (desc, ret, args, file, module, cond)

def qemu_function(name, desc, ret, args, file, module, cond):
    qemu_functions[name] = (desc, ret, args, file, module, cond)
186 187 188 189

def enum(type, name, value):
    if not enums.has_key(type):
        enums[type] = {}
190 191 192 193 194 195 196 197 198 199 200 201
    if value == 'VIR_TYPED_PARAM_INT':
        value = 1
    elif value == 'VIR_TYPED_PARAM_UINT':
        value = 2
    elif value == 'VIR_TYPED_PARAM_LLONG':
        value = 3
    elif value == 'VIR_TYPED_PARAM_ULLONG':
        value = 4
    elif value == 'VIR_TYPED_PARAM_DOUBLE':
        value = 5
    elif value == 'VIR_TYPED_PARAM_BOOLEAN':
        value = 6
202 203 204 205 206 207
    elif value == 'VIR_DOMAIN_AFFECT_CURRENT':
        value = 0
    elif value == 'VIR_DOMAIN_AFFECT_LIVE':
        value = 1
    elif value == 'VIR_DOMAIN_AFFECT_CONFIG':
        value = 2
208 209
    if name[-5:] != '_LAST':
        enums[type][name] = value
210

211 212 213 214 215 216
def qemu_enum(type, name, value):
    if not qemu_enums.has_key(type):
        qemu_enums[type] = {}
    qemu_enums[type][name] = value


217 218 219 220 221 222 223
#######################################################################
#
#  Some filtering rukes to drop functions/types which should not
#  be exposed as-is on the Python interface
#
#######################################################################

224
functions_failed = []
225
qemu_functions_failed = []
226
functions_skipped = [
227
    "virConnectListDomains",
228
]
229
qemu_functions_skipped = []
230

231 232 233 234
skipped_modules = {
}

skipped_types = {
235
#    'int *': "usually a return type",
236
     'virConnectDomainEventCallback': "No function types in python",
237
     'virConnectDomainEventGenericCallback': "No function types in python",
238
     'virConnectDomainEventRTCChangeCallback': "No function types in python",
239
     'virConnectDomainEventWatchdogCallback': "No function types in python",
240
     'virConnectDomainEventIOErrorCallback': "No function types in python",
241
     'virConnectDomainEventGraphicsCallback': "No function types in python",
242
     'virStreamEventCallback': "No function types in python",
243 244
     'virEventHandleCallback': "No function types in python",
     'virEventTimeoutCallback': "No function types in python",
245
     'virDomainBlockJobInfoPtr': "Not implemented yet",
246 247 248 249 250 251 252 253 254 255 256 257
}

#######################################################################
#
#  Table of remapping to/from the python type or class to the C
#  counterpart.
#
#######################################################################

py_types = {
    'void': (None, None, None, None),
    'int':  ('i', None, "int", "int"),
258
    'long':  ('l', None, "long", "long"),
259 260
    'double':  ('d', None, "double", "double"),
    'unsigned int':  ('i', None, "int", "int"),
261
    'unsigned long':  ('l', None, "long", "long"),
262
    'long long':  ('l', None, "longlong", "long long"),
263
    'unsigned long long':  ('l', None, "longlong", "long long"),
264 265
    'unsigned char *':  ('z', None, "charPtr", "char *"),
    'char *':  ('z', None, "charPtr", "char *"),
E
Eric Blake 已提交
266
    'const char *':  ('z', None, "constcharPtr", "const char *"),
267
    'size_t': ('n', None, "size_t", "size_t"),
268

269 270 271 272
    'virDomainPtr':  ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
    'const virDomainPtr':  ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
    'virDomain *':  ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
    'const virDomain *':  ('O', "virDomain", "virDomainPtr", "virDomainPtr"),
273

274 275 276 277
    'virNetworkPtr':  ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
    'const virNetworkPtr':  ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
    'virNetwork *':  ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
    'const virNetwork *':  ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"),
278

279 280 281 282 283
    'virInterfacePtr':  ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),
    'const virInterfacePtr':  ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),
    'virInterface *':  ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),
    'const virInterface *':  ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"),

284 285 286 287 288 289 290 291 292 293
    'virStoragePoolPtr':  ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),
    'const virStoragePoolPtr':  ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),
    'virStoragePool *':  ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),
    'const virStoragePool *':  ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"),

    'virStorageVolPtr':  ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),
    'const virStorageVolPtr':  ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),
    'virStorageVol *':  ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),
    'const virStorageVol *':  ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"),

294 295 296 297
    'virConnectPtr':  ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
    'const virConnectPtr':  ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
    'virConnect *':  ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
    'const virConnect *':  ('O', "virConnect", "virConnectPtr", "virConnectPtr"),
298 299 300 301 302

    'virNodeDevicePtr':  ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
    'const virNodeDevicePtr':  ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
    'virNodeDevice *':  ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
    'const virNodeDevice *':  ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"),
303 304 305 306 307

    'virSecretPtr':  ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
    'const virSecretPtr':  ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
    'virSecret *':  ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
    'const virSecret *':  ('O', "virSecret", "virSecretPtr", "virSecretPtr"),
308

309 310 311 312 313
    'virNWFilterPtr':  ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),
    'const virNWFilterPtr':  ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),
    'virNWFilter *':  ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),
    'const virNWFilter *':  ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"),

314 315 316 317
    'virStreamPtr':  ('O', "virStream", "virStreamPtr", "virStreamPtr"),
    'const virStreamPtr':  ('O', "virStream", "virStreamPtr", "virStreamPtr"),
    'virStream *':  ('O', "virStream", "virStreamPtr", "virStreamPtr"),
    'const virStream *':  ('O', "virStream", "virStreamPtr", "virStreamPtr"),
C
Chris Lalancette 已提交
318 319

    'virDomainSnapshotPtr':  ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
320 321 322
    'const virDomainSnapshotPtr':  ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
    'virDomainSnapshot *':  ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
    'const virDomainSnapshot *':  ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"),
323 324 325 326 327 328 329 330 331 332 333 334
}

py_return_types = {
}

unknown_types = {}

foreign_encoding_args = (
)

#######################################################################
#
335 336
#  This part writes the C <-> Python stubs libvirt.[ch] and
#  the table libvirt-export.c to add when registrering the Python module
337 338 339
#
#######################################################################

340
# Class methods which are written by hand in libvirt.c but the Python-level
341 342
# code is still automatically generated (so they are not in skip_function()).
skip_impl = (
T
Taizo ITO 已提交
343
    'virConnectGetVersion',
344
    'virConnectGetLibVersion',
345
    'virConnectListDomainsID',
346
    'virConnectListDefinedDomains',
347 348
    'virConnectListNetworks',
    'virConnectListDefinedNetworks',
349
    'virConnectListSecrets',
350
    'virConnectListInterfaces',
351 352 353 354
    'virConnectListStoragePools',
    'virConnectListDefinedStoragePools',
    'virConnectListStorageVols',
    'virConnectListDefinedStorageVols',
355
    'virConnectListDefinedInterfaces',
356
    'virConnectListNWFilters',
357
    'virDomainSnapshotListNames',
358
    'virDomainSnapshotListChildrenNames',
359 360
    'virConnGetLastError',
    'virGetLastError',
361
    'virDomainGetInfo',
J
Jiri Denemark 已提交
362
    'virDomainGetState',
363
    'virDomainGetControlInfo',
364
    'virDomainGetBlockInfo',
365
    'virDomainGetJobInfo',
366
    'virNodeGetInfo',
367
    'virDomainGetUUID',
368
    'virDomainGetUUIDString',
369
    'virDomainLookupByUUID',
370
    'virNetworkGetUUID',
371
    'virNetworkGetUUIDString',
372
    'virNetworkLookupByUUID',
373 374
    'virDomainGetAutostart',
    'virNetworkGetAutostart',
375 376
    'virDomainBlockStats',
    'virDomainInterfaceStats',
377
    'virDomainMemoryStats',
378
    'virNodeGetCellsFreeMemory',
379 380
    'virDomainGetSchedulerType',
    'virDomainGetSchedulerParameters',
381
    'virDomainGetSchedulerParametersFlags',
382
    'virDomainSetSchedulerParameters',
383
    'virDomainSetSchedulerParametersFlags',
384 385
    'virDomainSetBlkioParameters',
    'virDomainGetBlkioParameters',
386 387
    'virDomainSetMemoryParameters',
    'virDomainGetMemoryParameters',
388 389
    'virDomainSetNumaParameters',
    'virDomainGetNumaParameters',
390 391
    'virDomainGetVcpus',
    'virDomainPinVcpu',
392
    'virDomainPinVcpuFlags',
393
    'virDomainGetVcpuPinInfo',
394 395
    'virSecretGetValue',
    'virSecretSetValue',
396 397 398
    'virSecretGetUUID',
    'virSecretGetUUIDString',
    'virSecretLookupByUUID',
399 400 401
    'virNWFilterGetUUID',
    'virNWFilterGetUUIDString',
    'virNWFilterLookupByUUID',
402
    'virStoragePoolGetUUID',
403
    'virStoragePoolGetUUIDString',
404 405 406 407 408
    'virStoragePoolLookupByUUID',
    'virStoragePoolGetInfo',
    'virStorageVolGetInfo',
    'virStoragePoolGetAutostart',
    'virStoragePoolListVolumes',
409 410
    'virDomainBlockPeek',
    'virDomainMemoryPeek',
411
    'virEventRegisterImpl',
412 413
    'virNodeListDevices',
    'virNodeDeviceListCaps',
J
Jiri Denemark 已提交
414
    'virConnectBaselineCPU',
415
    'virDomainRevertToSnapshot',
416
    'virDomainSendKey',
M
Minoru Usui 已提交
417
    'virNodeGetCPUStats',
418
    'virNodeGetMemoryStats',
419
    'virDomainGetBlockJobInfo',
420
    'virDomainMigrateGetMaxSpeed',
421
    'virDomainBlockStatsFlags',
422 423
    'virDomainSetBlockIoTune',
    'virDomainGetBlockIoTune',
424 425
    'virDomainSetInterfaceParameters',
    'virDomainGetInterfaceParameters',
426
    'virDomainGetCPUStats',
427
    'virDomainGetDiskErrors',
428 429
    'virConnectUnregisterCloseCallback',
    'virConnectRegisterCloseCallback',
430 431
)

432 433
qemu_skip_impl = (
    'virDomainQemuMonitorCommand',
434
    'virDomainQemuAgentCommand',
435 436
)

437 438 439 440 441 442 443 444 445 446 447 448 449 450

# These are functions which the generator skips completly - no python
# or C code is generated. Generally should not be used for any more
# functions than those already listed
skip_function = (
    'virConnectListDomains', # Python API is called virConectListDomainsID for unknown reasons
    'virConnSetErrorFunc', # Not used in Python API  XXX is this a bug ?
    'virResetError', # Not used in Python API  XXX is this a bug ?
    'virGetVersion', # Python C code is manually written
    'virSetErrorFunc', # Python API is called virRegisterErrorHandler for unknown reasons
    'virConnCopyLastError', # Python API is called virConnGetLastError instead
    'virCopyLastError', # Python API is called virGetLastError instead
    'virConnectOpenAuth', # Python C code is manually written
    'virDefaultErrorFunc', # Python virErrorFuncHandler impl calls this from C
451
    'virDomainGetSecurityLabel', # Needs investigation...
M
Marcelo Cerri 已提交
452
    'virDomainGetSecurityLabelList', # Needs investigation...
453
    'virNodeGetSecurityModel', # Needs investigation...
454 455
    'virConnectDomainEventRegister',   # overridden in virConnect.py
    'virConnectDomainEventDeregister', # overridden in virConnect.py
456 457
    'virConnectDomainEventRegisterAny',   # overridden in virConnect.py
    'virConnectDomainEventDeregisterAny', # overridden in virConnect.py
458 459
    'virSaveLastError', # We have our own python error wrapper
    'virFreeError', # Only needed if we use virSaveLastError
460
    'virConnectListAllDomains', # overridden in virConnect.py
461 462
    'virDomainListAllSnapshots', # overridden in virDomain.py
    'virDomainSnapshotListAllChildren', # overridden in virDomainSnapshot.py
463
    'virConnectListAllStoragePools', # overridden in virConnect.py
464
    'virStoragePoolListAllVolumes', # overridden in virStoragePool.py
465
    'virConnectListAllNetworks', # overridden in virConnect.py
466
    'virConnectListAllInterfaces', # overridden in virConnect.py
467
    'virConnectListAllNodeDevices', # overridden in virConnect.py
468
    'virConnectListAllNWFilters', # overridden in virConnect.py
469

470 471
    'virStreamRecvAll', # Pure python libvirt-override-virStream.py
    'virStreamSendAll', # Pure python libvirt-override-virStream.py
472 473
    'virStreamRecv', # overridden in libvirt-override-virStream.py
    'virStreamSend', # overridden in libvirt-override-virStream.py
474

475
    # 'Ref' functions have no use for bindings users.
476 477 478 479 480 481
    "virConnectRef",
    "virDomainRef",
    "virInterfaceRef",
    "virNetworkRef",
    "virNodeDeviceRef",
    "virSecretRef",
482
    "virNWFilterRef",
483 484
    "virStoragePoolRef",
    "virStorageVolRef",
485
    'virStreamRef',
486 487 488 489 490 491 492 493

    # This functions shouldn't be called via the bindings (and even the docs
    # contain an explicit warning to that effect). The equivalent should be
    # implemented in pure python for each class
    "virDomainGetConnect",
    "virInterfaceGetConnect",
    "virNetworkGetConnect",
    "virSecretGetConnect",
494
    "virNWFilterGetConnect",
495 496
    "virStoragePoolGetConnect",
    "virStorageVolGetConnect",
497 498
)

499 500 501 502
qemu_skip_function = (
    #"virDomainQemuAttach",
)

503
# Generate C code, but skip python impl
504
function_skip_python_impl = (
505 506
    "virStreamFree", # Needed in custom virStream __del__, but free shouldn't
                     # be exposed in bindings
507
)
508

509 510
qemu_function_skip_python_impl = ()

511 512 513 514
function_skip_index_one = (
    "virDomainRevertToSnapshot",
)

515
def print_function_wrapper(module, name, output, export, include):
516 517 518
    global py_types
    global unknown_types
    global functions
519
    global qemu_functions
520
    global skipped_modules
521
    global function_skip_python_impl
522 523

    try:
524 525 526 527
        if module == "libvirt":
            (desc, ret, args, file, mod, cond) = functions[name]
        if module == "libvirt-qemu":
            (desc, ret, args, file, mod, cond) = qemu_functions[name]
528
    except:
529
        print "failed to get function %s infos" % name
530 531
        return

532
    if skipped_modules.has_key(module):
533
        return 0
534 535 536 537 538 539 540 541 542 543 544 545 546

    if module == "libvirt":
        if name in skip_function:
            return 0
        if name in skip_impl:
            # Don't delete the function entry in the caller.
            return 1
    elif module == "libvirt-qemu":
        if name in qemu_skip_function:
            return 0
        if name in qemu_skip_impl:
            # Don't delete the function entry in the caller.
            return 1
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561

    c_call = "";
    format=""
    format_args=""
    c_args=""
    c_return=""
    c_convert=""
    num_bufs=0
    for arg in args:
        # This should be correct
        if arg[1][0:6] == "const ":
            arg[1] = arg[1][6:]
        c_args = c_args + "    %s %s;\n" % (arg[1], arg[0])
        if py_types.has_key(arg[1]):
            (f, t, n, c) = py_types[arg[1]]
562 563
            if (f == 'z') and (name in foreign_encoding_args) and (num_bufs == 0):
                f = 't#'
564 565 566 567 568 569 570 571 572 573
            if f != None:
                format = format + f
            if t != None:
                format_args = format_args + ", &pyobj_%s" % (arg[0])
                c_args = c_args + "    PyObject *pyobj_%s;\n" % (arg[0])
                c_convert = c_convert + \
                   "    %s = (%s) Py%s_Get(pyobj_%s);\n" % (arg[0],
                   arg[1], t, arg[0]);
            else:
                format_args = format_args + ", &%s" % (arg[0])
574 575 576 577
            if f == 't#':
                format_args = format_args + ", &py_buffsize%d" % num_bufs
                c_args = c_args + "    int py_buffsize%d;\n" % num_bufs
                num_bufs = num_bufs + 1
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
            if c_call != "":
                c_call = c_call + ", ";
            c_call = c_call + "%s" % (arg[0])
        else:
            if skipped_types.has_key(arg[1]):
                return 0
            if unknown_types.has_key(arg[1]):
                lst = unknown_types[arg[1]]
                lst.append(name)
            else:
                unknown_types[arg[1]] = [name]
            return -1
    if format != "":
        format = format + ":%s" % (name)

    if ret[0] == 'void':
        if file == "python_accessor":
595
            if args[1][1] == "char *":
596
                c_call = "\n    VIR_FREE(%s->%s);\n" % (
597 598 599 600 601 602
                                 args[0][0], args[1][0], args[0][0], args[1][0])
                c_call = c_call + "    %s->%s = (%s)strdup((const xmlChar *)%s);\n" % (args[0][0],
                                 args[1][0], args[1][1], args[1][0])
            else:
                c_call = "\n    %s->%s = %s;\n" % (args[0][0], args[1][0],
                                                   args[1][0])
603 604
        else:
            c_call = "\n    %s(%s);\n" % (name, c_call);
605
        ret_convert = "    Py_INCREF(Py_None);\n    return Py_None;\n"
606 607 608 609 610 611 612
    elif py_types.has_key(ret[0]):
        (f, t, n, c) = py_types[ret[0]]
        c_return = "    %s c_retval;\n" % (ret[0])
        if file == "python_accessor" and ret[2] != None:
            c_call = "\n    c_retval = %s->%s;\n" % (args[0][0], ret[2])
        else:
            c_call = "\n    c_retval = %s(%s);\n" % (name, c_call);
613
        ret_convert = "    py_retval = libvirt_%sWrap((%s) c_retval);\n" % (n,c)
614
        ret_convert = ret_convert + "    return py_retval;\n"
615 616 617 618
    elif py_return_types.has_key(ret[0]):
        (f, t, n, c) = py_return_types[ret[0]]
        c_return = "    %s c_retval;\n" % (ret[0])
        c_call = "\n    c_retval = %s(%s);\n" % (name, c_call);
619
        ret_convert = "    py_retval = libvirt_%sWrap((%s) c_retval);\n" % (n,c)
620
        ret_convert = ret_convert + "    return py_retval;\n"
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    else:
        if skipped_types.has_key(ret[0]):
            return 0
        if unknown_types.has_key(ret[0]):
            lst = unknown_types[ret[0]]
            lst.append(name)
        else:
            unknown_types[ret[0]] = [name]
        return -1

    if cond != None and cond != "":
        include.write("#if %s\n" % cond)
        export.write("#if %s\n" % cond)
        output.write("#if %s\n" % cond)

    include.write("PyObject * ")
637 638 639 640 641 642 643 644
    if module == "libvirt":
        include.write("libvirt_%s(PyObject *self, PyObject *args);\n" % (name));
        export.write("    { (char *)\"%s\", libvirt_%s, METH_VARARGS, NULL },\n" %
                     (name, name))
    elif module == "libvirt-qemu":
        include.write("libvirt_qemu_%s(PyObject *self, PyObject *args);\n" % (name));
        export.write("    { (char *)\"%s\", libvirt_qemu_%s, METH_VARARGS, NULL },\n" %
                     (name, name))
645 646 647

    if file == "python":
        # Those have been manually generated
648 649 650 651
        if cond != None and cond != "":
            include.write("#endif\n");
            export.write("#endif\n");
            output.write("#endif\n");
652 653 654
        return 1
    if file == "python_accessor" and ret[0] != "void" and ret[2] is None:
        # Those have been manually generated
655 656 657 658
        if cond != None and cond != "":
            include.write("#endif\n");
            export.write("#endif\n");
            output.write("#endif\n");
659 660 661
        return 1

    output.write("PyObject *\n")
662 663 664 665
    if module == "libvirt":
        output.write("libvirt_%s(PyObject *self ATTRIBUTE_UNUSED," % (name))
    elif module == "libvirt-qemu":
        output.write("libvirt_qemu_%s(PyObject *self ATTRIBUTE_UNUSED," % (name))
666 667
    output.write(" PyObject *args")
    if format == "":
668
        output.write(" ATTRIBUTE_UNUSED")
669 670 671 672 673 674 675 676 677 678
    output.write(") {\n")
    if ret[0] != 'void':
        output.write("    PyObject *py_retval;\n")
    if c_return != "":
        output.write(c_return)
    if c_args != "":
        output.write(c_args)
    if format != "":
        output.write("\n    if (!PyArg_ParseTuple(args, (char *)\"%s\"%s))\n" %
                     (format, format_args))
679
        output.write("        return NULL;\n")
680
    if c_convert != "":
681
        output.write(c_convert + "\n")
682

683
    output.write("    LIBVIRT_BEGIN_ALLOW_THREADS;");
684
    output.write(c_call);
685
    output.write("    LIBVIRT_END_ALLOW_THREADS;\n");
686 687 688 689 690 691
    output.write(ret_convert)
    output.write("}\n\n")
    if cond != None and cond != "":
        include.write("#endif /* %s */\n" % cond)
        export.write("#endif /* %s */\n" % cond)
        output.write("#endif /* %s */\n" % cond)
692

693 694 695 696 697 698
    if module == "libvirt":
        if name in function_skip_python_impl:
            return 0
    elif module == "libvirt-qemu":
        if name in qemu_function_skip_python_impl:
            return 0
699 700
    return 1

701
def buildStubs(module):
702 703 704 705
    global py_types
    global py_return_types
    global unknown_types

706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
    if module not in ["libvirt", "libvirt-qemu"]:
        print "ERROR: Unknown module type: %s" % module
        return None

    if module == "libvirt":
        funcs = functions
        funcs_failed = functions_failed
        funcs_skipped = functions_skipped
    elif module == "libvirt-qemu":
        funcs = qemu_functions
        funcs_failed = qemu_functions_failed
        funcs_skipped = functions_skipped

    api_xml = "%s-api.xml" % module

721
    try:
722
        f = open(os.path.join(srcPref,api_xml))
723 724 725 726
        data = f.read()
        (parser, target)  = getparser()
        parser.feed(data)
        parser.close()
727
    except IOError, msg:
728
        try:
729
            f = open(os.path.join(srcPref,"..","docs",api_xml))
730 731 732 733 734 735 736
            data = f.read()
            (parser, target)  = getparser()
            parser.feed(data)
            parser.close()
        except IOError, msg:
            print file, ":", msg
            sys.exit(1)
737

738
    n = len(funcs.keys())
739
    if not quiet:
740
        print "Found %d functions in %s" % ((n), api_xml)
741

742
    override_api_xml = "%s-override-api.xml" % module
743
    py_types['pythonObject'] = ('O', "pythonObject", "pythonObject", "pythonObject")
744

745
    try:
746
        f = open(os.path.join(srcPref, override_api_xml))
747 748 749 750
        data = f.read()
        (parser, target)  = getparser()
        parser.feed(data)
        parser.close()
751
    except IOError, msg:
752
        print file, ":", msg
753

754
    if not quiet:
755 756 757
        # XXX: This is not right, same function already in @functions
        # will be overwritten.
        print "Found %d functions in %s" % ((len(funcs.keys()) - n), override_api_xml)
758 759 760 761
    nb_wrap = 0
    failed = 0
    skipped = 0

762 763 764 765 766
    header_file = "%s.h" % module
    export_file = "%s-export.c" % module
    wrapper_file = "%s.c" % module

    include = open(header_file, "w")
767
    include.write("/* Generated */\n\n")
768 769

    export = open(export_file, "w")
770
    export.write("/* Generated */\n\n")
771 772

    wrapper = open(wrapper_file, "w")
773 774
    wrapper.write("/* Generated by generator.py */\n\n")
    wrapper.write("#include <config.h>\n")
775
    wrapper.write("#include <Python.h>\n")
776
    wrapper.write("#include <libvirt/" + module + ".h>\n")
777
    wrapper.write("#include \"typewrappers.h\"\n")
778 779 780 781 782
    wrapper.write("#include \"" + module + ".h\"\n\n")

    for function in funcs.keys():
        # Skip the functions which are not for the module
        ret = print_function_wrapper(module, function, wrapper, export, include)
783 784
        if ret < 0:
            failed = failed + 1
785 786
            funcs_failed.append(function)
            del funcs[function]
787 788
        if ret == 0:
            skipped = skipped + 1
789 790
            funcs_skipped.append(function)
            del funcs[function]
791 792
        if ret == 1:
            nb_wrap = nb_wrap + 1
793 794 795 796
    include.close()
    export.close()
    wrapper.close()

797 798
    if not quiet:
        print "Generated %d wrapper functions" % nb_wrap
799

800 801 802 803 804
    if unknown_types:
        print "Missing type converters: "
        for type in unknown_types.keys():
            print "%s:%d " % (type, len(unknown_types[type])),

805
    for f in funcs_failed:
806 807 808 809
        print "ERROR: failed %s" % f

    if failed > 0:
        return -1
810 811
    if len(unknown_types) > 0:
        return -1
812 813
    return 0

814 815 816 817 818 819 820 821 822 823 824 825
#######################################################################
#
#  This part writes part of the Python front-end classes based on
#  mapping rules between types and classes and also based on function
#  renaming to get consistent function names at the Python level
#
#######################################################################

#
# The type automatically remapped to generated classes
#
classes_type = {
826 827 828 829
    "virDomainPtr": ("._o", "virDomain(self,_obj=%s)", "virDomain"),
    "virDomain *": ("._o", "virDomain(self, _obj=%s)", "virDomain"),
    "virNetworkPtr": ("._o", "virNetwork(self, _obj=%s)", "virNetwork"),
    "virNetwork *": ("._o", "virNetwork(self, _obj=%s)", "virNetwork"),
830 831
    "virInterfacePtr": ("._o", "virInterface(self, _obj=%s)", "virInterface"),
    "virInterface *": ("._o", "virInterface(self, _obj=%s)", "virInterface"),
832 833 834 835
    "virStoragePoolPtr": ("._o", "virStoragePool(self, _obj=%s)", "virStoragePool"),
    "virStoragePool *": ("._o", "virStoragePool(self, _obj=%s)", "virStoragePool"),
    "virStorageVolPtr": ("._o", "virStorageVol(self, _obj=%s)", "virStorageVol"),
    "virStorageVol *": ("._o", "virStorageVol(self, _obj=%s)", "virStorageVol"),
836 837
    "virNodeDevicePtr": ("._o", "virNodeDevice(self, _obj=%s)", "virNodeDevice"),
    "virNodeDevice *": ("._o", "virNodeDevice(self, _obj=%s)", "virNodeDevice"),
838 839
    "virSecretPtr": ("._o", "virSecret(self, _obj=%s)", "virSecret"),
    "virSecret *": ("._o", "virSecret(self, _obj=%s)", "virSecret"),
840 841
    "virNWFilterPtr": ("._o", "virNWFilter(self, _obj=%s)", "virNWFilter"),
    "virNWFilter *": ("._o", "virNWFilter(self, _obj=%s)", "virNWFilter"),
842 843
    "virStreamPtr": ("._o", "virStream(self, _obj=%s)", "virStream"),
    "virStream *": ("._o", "virStream(self, _obj=%s)", "virStream"),
844 845
    "virConnectPtr": ("._o", "virConnect(_obj=%s)", "virConnect"),
    "virConnect *": ("._o", "virConnect(_obj=%s)", "virConnect"),
846 847
    "virDomainSnapshotPtr": ("._o", "virDomainSnapshot(self,_obj=%s)", "virDomainSnapshot"),
    "virDomainSnapshot *": ("._o", "virDomainSnapshot(self, _obj=%s)", "virDomainSnapshot"),
848 849 850 851 852
}

converter_type = {
}

853 854
primary_classes = ["virDomain", "virNetwork", "virInterface",
                   "virStoragePool", "virStorageVol",
855
                   "virConnect", "virNodeDevice", "virSecret",
856
                   "virNWFilter", "virStream", "virDomainSnapshot"]
857 858 859

classes_ancestor = {
}
860

861 862
classes_destructors = {
    "virDomain": "virDomainFree",
863
    "virNetwork": "virNetworkFree",
864
    "virInterface": "virInterfaceFree",
865 866
    "virStoragePool": "virStoragePoolFree",
    "virStorageVol": "virStorageVolFree",
867
    "virNodeDevice" : "virNodeDeviceFree",
868
    "virSecret": "virSecretFree",
869
    "virNWFilter": "virNWFilterFree",
870
    "virDomainSnapshot": "virDomainSnapshotFree",
871 872
    # We hand-craft __del__ for this one
    #"virStream": "virStreamFree",
873 874
}

875
class_skip_connect_impl = {
876 877
    "virConnect" : True,
    "virDomainSnapshot": True,
878 879
}

880 881 882
class_domain_impl = {
    "virDomainSnapshot": True,
}
883

884
functions_noexcept = {
885 886
    'virDomainGetID': True,
    'virDomainGetName': True,
887
    'virNetworkGetName': True,
888
    'virInterfaceGetName': True,
889 890 891
    'virStoragePoolGetName': True,
    'virStorageVolGetName': True,
    'virStorageVolGetkey': True,
892 893
    'virNodeDeviceGetName': True,
    'virNodeDeviceGetParent': True,
894 895
    'virSecretGetUsageType': True,
    'virSecretGetUsageID': True,
896
    'virNWFilterGetName': True,
897 898 899 900 901 902 903 904 905
}

reference_keepers = {
}

function_classes = {}

function_classes["None"] = []

906
function_post = {}
907

908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
# Functions returning an integral type which need special rules to
# check for errors and raise exceptions.
functions_int_exception_test = {
    'virDomainGetMaxMemory': "%s == 0",
}
functions_int_default_test = "%s == -1"

def is_integral_type (name):
    return not re.search ("^(unsigned)? ?(int|long)$", name) is None

# Functions returning lists which need special rules to check for errors
# and raise exceptions.
functions_list_exception_test = {
}
functions_list_default_test = "%s is None"

def is_list_type (name):
925 926 927 928
    whitelist = [ "virDomainBlockStats",
                  "virDomainInterfaceStats" ]

    return name[-1:] == "*" or name in whitelist
929

930
def nameFixup(name, classe, type, file):
931
    # avoid a desastrous clash
932 933 934 935 936 937
    listname = classe + "List"
    ll = len(listname)
    l = len(classe)
    if name[0:l] == listname:
        func = name[l:]
        func = string.lower(func[0:1]) + func[1:]
938 939 940
    elif name[0:16] == "virNetworkDefine":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
941 942 943
    elif name[0:19] == "virNetworkCreateXML":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
944
    elif name[0:16] == "virNetworkLookup":
945 946
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
947 948 949 950 951 952 953 954 955
    elif name[0:18] == "virInterfaceDefine":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:21] == "virInterfaceCreateXML":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:18] == "virInterfaceLookup":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
956 957 958 959 960 961
    elif name[0:15] == "virSecretDefine":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:15] == "virSecretLookup":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
962 963 964 965 966 967
    elif name[0:17] == "virNWFilterDefine":
        func = name[3:]
        func = string.lower(func[0:3]) + func[3:]
    elif name[0:17] == "virNWFilterLookup":
        func = name[3:]
        func = string.lower(func[0:3]) + func[3:]
968 969 970
    elif name[0:20] == "virStoragePoolDefine":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
971 972 973
    elif name[0:23] == "virStoragePoolCreateXML":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
974 975 976 977 978 979 980 981 982
    elif name[0:20] == "virStoragePoolLookup":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:19] == "virStorageVolDefine":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:19] == "virStorageVolLookup":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
983 984 985
    elif name[0:20] == "virDomainGetCPUStats":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
986 987 988
    elif name[0:12] == "virDomainGet":
        func = name[12:]
        func = string.lower(func[0:1]) + func[1:]
989 990 991 992 993 994
    elif name[0:29] == "virDomainSnapshotLookupByName":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:26] == "virDomainSnapshotListNames":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
995 996 997
    elif name[0:28] == "virDomainSnapshotNumChildren":
        func = name[17:]
        func = string.lower(func[0:1]) + func[1:]
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    elif name[0:20] == "virDomainSnapshotNum":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:26] == "virDomainSnapshotCreateXML":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:24] == "virDomainSnapshotCurrent":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:17] == "virDomainSnapshot":
        func = name[17:]
        func = string.lower(func[0:1]) + func[1:]
1010 1011 1012
    elif name[0:9] == "virDomain":
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
1013 1014 1015 1016 1017 1018
    elif name[0:13] == "virNetworkGet":
        func = name[13:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:10] == "virNetwork":
        func = name[10:]
        func = string.lower(func[0:1]) + func[1:]
1019
    elif name[0:15] == "virInterfaceGet":
1020
        func = name[15:]
1021 1022
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:12] == "virInterface":
1023
        func = name[12:]
1024
        func = string.lower(func[0:1]) + func[1:]
1025 1026 1027 1028 1029 1030
    elif name[0:12] == 'virSecretGet':
        func = name[12:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:9] == 'virSecret':
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
1031 1032 1033 1034 1035 1036
    elif name[0:14] == 'virNWFilterGet':
        func = name[14:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:11] == 'virNWFilter':
        func = name[11:]
        func = string.lower(func[0:1]) + func[1:]
1037 1038 1039 1040 1041
    elif name[0:12] == 'virStreamNew':
        func = "newStream"
    elif name[0:9] == 'virStream':
        func = name[9:]
        func = string.lower(func[0:1]) + func[1:]
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
    elif name[0:17] == "virStoragePoolGet":
        func = name[17:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:14] == "virStoragePool":
        func = name[14:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:16] == "virStorageVolGet":
        func = name[16:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:13] == "virStorageVol":
        func = name[13:]
        func = string.lower(func[0:1]) + func[1:]
1054 1055 1056
    elif name[0:13] == "virNodeDevice":
        if name[13:16] == "Get":
            func = string.lower(name[16]) + name[17:]
1057
        elif name[13:19] == "Lookup" or name[13:19] == "Create":
1058 1059 1060
            func = string.lower(name[3]) + name[4:]
        else:
            func = string.lower(name[13]) + name[14:]
1061 1062 1063
    elif name[0:7] == "virNode":
        func = name[7:]
        func = string.lower(func[0:1]) + func[1:]
1064 1065 1066 1067 1068 1069 1070 1071
    elif name[0:10] == "virConnect":
        func = name[10:]
        func = string.lower(func[0:1]) + func[1:]
    elif name[0:3] == "xml":
        func = name[3:]
        func = string.lower(func[0:1]) + func[1:]
    else:
        func = name
1072 1073
    if func == "iD":
        func = "ID"
1074 1075
    if func == "uUID":
        func = "UUID"
1076 1077
    if func == "uUIDString":
        func = "UUIDString"
1078 1079 1080 1081
    if func == "oSType":
        func = "OSType"
    if func == "xMLDesc":
        func = "XMLDesc"
1082 1083 1084
    if func == "mACString":
        func = "MACString"

1085 1086 1087 1088
    return func


def functionCompare(info1, info2):
1089 1090
    (index1, func1, name1, ret1, args1, file1, mod1) = info1
    (index2, func2, name2, ret2, args2, file2, mod2) = info2
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
    if file1 == file2:
        if func1 < func2:
            return -1
        if func1 > func2:
            return 1
    if file1 == "python_accessor":
        return -1
    if file2 == "python_accessor":
        return 1
    if file1 < file2:
        return -1
    if file1 > file2:
        return 1
    return 0

1106 1107 1108 1109 1110 1111
def writeDoc(module, name, args, indent, output):
     if module == "libvirt":
         funcs = functions
     elif module == "libvirt-qemu":
         funcs = qemu_functions
     if funcs[name][0] is None or funcs[name][0] == "":
1112
         return
1113
     val = funcs[name][0]
1114 1115 1116
     val = string.replace(val, "NULL", "None");
     output.write(indent)
     output.write('"""')
1117 1118 1119 1120
     i = string.find(val, "\n")
     while i >= 0:
         str = val[0:i+1]
         val = val[i+1:]
1121
         output.write(str)
1122
         i = string.find(val, "\n")
1123
         output.write(indent)
1124
     output.write(val)
1125 1126
     output.write(' """\n')

1127
def buildWrappers(module):
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    global ctypes
    global py_types
    global py_return_types
    global unknown_types
    global functions
    global function_classes
    global classes_type
    global classes_list
    global converter_type
    global primary_classes
    global converter_type
    global classes_ancestor
    global converter_type
    global primary_classes
    global classes_destructors
    global functions_noexcept

1145 1146 1147 1148
    if not module == "libvirt":
        print "ERROR: Unknown module type: %s" % module
        return None

1149
    for type in classes_type.keys():
1150
        function_classes[classes_type[type][2]] = []
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

    #
    # Build the list of C types to look for ordered to start
    # with primary classes
    #
    ctypes = []
    classes_list = []
    ctypes_processed = {}
    classes_processed = {}
    for classe in primary_classes:
1161 1162 1163 1164 1165 1166 1167
        classes_list.append(classe)
        classes_processed[classe] = ()
        for type in classes_type.keys():
            tinfo = classes_type[type]
            if tinfo[2] == classe:
                ctypes.append(type)
                ctypes_processed[type] = ()
1168
    for type in classes_type.keys():
1169 1170 1171 1172 1173 1174
        if ctypes_processed.has_key(type):
            continue
        tinfo = classes_type[type]
        if not classes_processed.has_key(tinfo[2]):
            classes_list.append(tinfo[2])
            classes_processed[tinfo[2]] = ()
1175

1176 1177
        ctypes.append(type)
        ctypes_processed[type] = ()
1178 1179

    for name in functions.keys():
1180
        found = 0;
1181
        (desc, ret, args, file, mod, cond) = functions[name]
1182 1183 1184 1185 1186 1187
        for type in ctypes:
            classe = classes_type[type][2]

            if name[0:3] == "vir" and len(args) >= 1 and args[0][1] == type:
                found = 1
                func = nameFixup(name, classe, type, file)
1188
                info = (0, func, name, ret, args, file, mod)
1189 1190 1191 1192 1193
                function_classes[classe].append(info)
            elif name[0:3] == "vir" and len(args) >= 2 and args[1][1] == type \
                and file != "python_accessor" and not name in function_skip_index_one:
                found = 1
                func = nameFixup(name, classe, type, file)
1194
                info = (1, func, name, ret, args, file, mod)
1195 1196 1197 1198
                function_classes[classe].append(info)
        if found == 1:
            continue
        func = nameFixup(name, "None", file, file)
1199
        info = (0, func, name, ret, args, file, mod)
1200
        function_classes['None'].append(info)
1201

1202
    classes_file = "%s.py" % module
1203
    extra_file = os.path.join(srcPref, "%s-override.py" % module)
1204 1205 1206
    extra = None

    classes = open(classes_file, "w")
1207

1208
    if os.path.exists(extra_file):
1209
        extra = open(extra_file, "r")
1210
    classes.write("#! " + python + " -i\n")
1211 1212 1213 1214 1215 1216
    classes.write("#\n")
    classes.write("# WARNING WARNING WARNING WARNING\n")
    classes.write("#\n")
    classes.write("# This file is automatically written by generator.py. Any changes\n")
    classes.write("# made here will be lost.\n")
    classes.write("#\n")
1217
    classes.write("# To change the manually written methods edit " + module + "-override.py\n")
1218 1219 1220 1221
    classes.write("# To change the automatically written methods edit generator.py\n")
    classes.write("#\n")
    classes.write("# WARNING WARNING WARNING WARNING\n")
    classes.write("#\n")
1222 1223
    if extra != None:
        classes.writelines(extra.readlines())
1224 1225 1226 1227 1228 1229
    classes.write("#\n")
    classes.write("# WARNING WARNING WARNING WARNING\n")
    classes.write("#\n")
    classes.write("# Automatically written part of python bindings for libvirt\n")
    classes.write("#\n")
    classes.write("# WARNING WARNING WARNING WARNING\n")
1230 1231
    if extra != None:
        extra.close()
1232 1233

    if function_classes.has_key("None"):
1234 1235 1236 1237
        flist = function_classes["None"]
        flist.sort(functionCompare)
        oldfile = ""
        for info in flist:
1238
            (index, func, name, ret, args, file, mod) = info
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
            if file != oldfile:
                classes.write("#\n# Functions from module %s\n#\n\n" % file)
                oldfile = file
            classes.write("def %s(" % func)
            n = 0
            for arg in args:
                if n != 0:
                    classes.write(", ")
                classes.write("%s" % arg[0])
                n = n + 1
            classes.write("):\n")
1250
            writeDoc(module, name, args, '    ', classes);
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271

            for arg in args:
                if classes_type.has_key(arg[1]):
                    classes.write("    if %s is None: %s__o = None\n" %
                                  (arg[0], arg[0]))
                    classes.write("    else: %s__o = %s%s\n" %
                                  (arg[0], arg[0], classes_type[arg[1]][0]))
            if ret[0] != "void":
                classes.write("    ret = ");
            else:
                classes.write("    ");
            classes.write("libvirtmod.%s(" % name)
            n = 0
            for arg in args:
                if n != 0:
                    classes.write(", ");
                classes.write("%s" % arg[0])
                if classes_type.has_key(arg[1]):
                    classes.write("__o");
                n = n + 1
            classes.write(")\n");
1272 1273

            if ret[0] != "void":
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
                if classes_type.has_key(ret[0]):
                    #
                    # Raise an exception
                    #
                    if functions_noexcept.has_key(name):
                        classes.write("    if ret is None:return None\n");
                    else:
                        classes.write(
                     "    if ret is None:raise libvirtError('%s() failed')\n" %
                                      (name))

                    classes.write("    return ");
                    classes.write(classes_type[ret[0]][1] % ("ret"));
                    classes.write("\n");
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300

                # For functions returning an integral type there are
                # several things that we can do, depending on the
                # contents of functions_int_*:
                elif is_integral_type (ret[0]):
                    if not functions_noexcept.has_key (name):
                        if functions_int_exception_test.has_key (name):
                            test = functions_int_exception_test[name]
                        else:
                            test = functions_int_default_test
                        classes.write (("    if " + test +
                                        ": raise libvirtError ('%s() failed')\n") %
                                       ("ret", name))
1301
                    classes.write("    return ret\n")
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311

                elif is_list_type (ret[0]):
                    if not functions_noexcept.has_key (name):
                        if functions_list_exception_test.has_key (name):
                            test = functions_list_exception_test[name]
                        else:
                            test = functions_list_default_test
                        classes.write (("    if " + test +
                                        ": raise libvirtError ('%s() failed')\n") %
                                       ("ret", name))
1312
                    classes.write("    return ret\n")
1313

1314 1315
                else:
                    classes.write("    return ret\n")
1316

1317
            classes.write("\n");
1318 1319

    for classname in classes_list:
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
        if classname == "None":
            pass
        else:
            if classes_ancestor.has_key(classname):
                classes.write("class %s(%s):\n" % (classname,
                              classes_ancestor[classname]))
                classes.write("    def __init__(self, _obj=None):\n")
                if reference_keepers.has_key(classname):
                    rlist = reference_keepers[classname]
                    for ref in rlist:
                        classes.write("        self.%s = None\n" % ref[1])
                classes.write("        self._o = _obj\n")
                classes.write("        %s.__init__(self, _obj=_obj)\n\n" % (
                              classes_ancestor[classname]))
            else:
                classes.write("class %s:\n" % (classname))
1336
                if classname in [ "virDomain", "virNetwork", "virInterface", "virStoragePool",
1337 1338
                                  "virStorageVol", "virNodeDevice", "virSecret","virStream",
                                  "virNWFilter" ]:
1339
                    classes.write("    def __init__(self, conn, _obj=None):\n")
1340 1341
                elif classname in [ 'virDomainSnapshot' ]:
                    classes.write("    def __init__(self, dom, _obj=None):\n")
1342 1343
                else:
                    classes.write("    def __init__(self, _obj=None):\n")
1344 1345 1346 1347
                if reference_keepers.has_key(classname):
                    list = reference_keepers[classname]
                    for ref in list:
                        classes.write("        self.%s = None\n" % ref[1])
1348
                if classname in [ "virDomain", "virNetwork", "virInterface",
1349 1350
                                  "virNodeDevice", "virSecret", "virStream",
                                  "virNWFilter" ]:
1351
                    classes.write("        self._conn = conn\n")
1352 1353 1354 1355
                elif classname in [ "virStorageVol", "virStoragePool" ]:
                    classes.write("        self._conn = conn\n" + \
                                  "        if not isinstance(conn, virConnect):\n" + \
                                  "            self._conn = conn._conn\n")
1356 1357
                elif classname in [ "virDomainSnapshot" ]:
                    classes.write("        self._dom = dom\n")
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
                classes.write("        if _obj != None:self._o = _obj;return\n")
                classes.write("        self._o = None\n\n");
            destruct=None
            if classes_destructors.has_key(classname):
                classes.write("    def __del__(self):\n")
                classes.write("        if self._o != None:\n")
                classes.write("            libvirtmod.%s(self._o)\n" %
                              classes_destructors[classname]);
                classes.write("        self._o = None\n\n");
                destruct=classes_destructors[classname]
1368 1369 1370 1371 1372 1373

            if not class_skip_connect_impl.has_key(classname):
                # Build python safe 'connect' method
                classes.write("    def connect(self):\n")
                classes.write("        return self._conn\n\n")

1374 1375 1376 1377
            if class_domain_impl.has_key(classname):
                classes.write("    def domain(self):\n")
                classes.write("        return self._dom\n\n")

1378 1379 1380 1381
            flist = function_classes[classname]
            flist.sort(functionCompare)
            oldfile = ""
            for info in flist:
1382
                (index, func, name, ret, args, file, mod) = info
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
                #
                # Do not provide as method the destructors for the class
                # to avoid double free
                #
                if name == destruct:
                    continue;
                if file != oldfile:
                    if file == "python_accessor":
                        classes.write("    # accessors for %s\n" % (classname))
                    else:
                        classes.write("    #\n")
                        classes.write("    # %s functions from module %s\n" % (
                                      classname, file))
                        classes.write("    #\n\n")
                oldfile = file
                classes.write("    def %s(self" % func)
                n = 0
                for arg in args:
                    if n != index:
                        classes.write(", %s" % arg[0])
                    n = n + 1
                classes.write("):\n")
1405
                writeDoc(module, name, args, '        ', classes);
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
                n = 0
                for arg in args:
                    if classes_type.has_key(arg[1]):
                        if n != index:
                            classes.write("        if %s is None: %s__o = None\n" %
                                          (arg[0], arg[0]))
                            classes.write("        else: %s__o = %s%s\n" %
                                          (arg[0], arg[0], classes_type[arg[1]][0]))
                    n = n + 1
                if ret[0] != "void":
                    classes.write("        ret = ");
                else:
                    classes.write("        ");
                n = 0
1420
                classes.write("libvirtmod.%s(" % name)
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
                for arg in args:
                    if n != 0:
                        classes.write(", ");
                    if n != index:
                        classes.write("%s" % arg[0])
                        if classes_type.has_key(arg[1]):
                            classes.write("__o");
                    else:
                        classes.write("self");
                        if classes_type.has_key(arg[1]):
                            classes.write(classes_type[arg[1]][0])
                    n = n + 1
                classes.write(")\n");
1434

1435 1436 1437
                if name == "virConnectClose":
                    classes.write("        self._o = None\n")

1438 1439
                # For functions returning object types:
                if ret[0] != "void":
1440 1441 1442 1443 1444 1445 1446 1447
                    if classes_type.has_key(ret[0]):
                        #
                        # Raise an exception
                        #
                        if functions_noexcept.has_key(name):
                            classes.write(
                                "        if ret is None:return None\n");
                        else:
1448 1449
                            if classname == "virConnect":
                                classes.write(
1450
                     "        if ret is None:raise libvirtError('%s() failed', conn=self)\n" %
1451
                                              (name))
1452 1453
                            elif classname == "virDomain":
                                classes.write(
1454
                     "        if ret is None:raise libvirtError('%s() failed', dom=self)\n" %
1455 1456 1457
                                              (name))
                            elif classname == "virNetwork":
                                classes.write(
1458
                     "        if ret is None:raise libvirtError('%s() failed', net=self)\n" %
1459 1460 1461
                                              (name))
                            elif classname == "virInterface":
                                classes.write(
1462
                     "        if ret is None:raise libvirtError('%s() failed', net=self)\n" %
1463
                                              (name))
1464 1465
                            elif classname == "virStoragePool":
                                classes.write(
1466
                     "        if ret is None:raise libvirtError('%s() failed', pool=self)\n" %
1467 1468 1469
                                              (name))
                            elif classname == "virStorageVol":
                                classes.write(
1470
                     "        if ret is None:raise libvirtError('%s() failed', vol=self)\n" %
1471
                                              (name))
1472 1473 1474 1475
                            elif classname == "virDomainSnapshot":
                                classes.write(
                     "        if ret is None:raise libvirtError('%s() failed', dom=self._dom)\n" %
                                              (name))
1476 1477
                            else:
                                classes.write(
1478
                     "        if ret is None:raise libvirtError('%s() failed')\n" %
1479
                                              (name))
1480

1481 1482 1483 1484 1485 1486
                        #
                        # generate the returned class wrapper for the object
                        #
                        classes.write("        __tmp = ");
                        classes.write(classes_type[ret[0]][1] % ("ret"));
                        classes.write("\n");
1487 1488

                        #
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
                        # Sometime one need to keep references of the source
                        # class in the returned class object.
                        # See reference_keepers for the list
                        #
                        tclass = classes_type[ret[0]][2]
                        if reference_keepers.has_key(tclass):
                            list = reference_keepers[tclass]
                            for pref in list:
                                if pref[0] == classname:
                                    classes.write("        __tmp.%s = self\n" %
                                                  pref[1])
1500 1501 1502 1503 1504 1505

                        # Post-processing - just before we return.
                        if function_post.has_key(name):
                            classes.write("        %s\n" %
                                          (function_post[name]));

1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
                        #
                        # return the class
                        #
                        classes.write("        return __tmp\n");
                    elif converter_type.has_key(ret[0]):
                        #
                        # Raise an exception
                        #
                        if functions_noexcept.has_key(name):
                            classes.write(
                                "        if ret is None:return None");
1517 1518 1519 1520 1521 1522

                        # Post-processing - just before we return.
                        if function_post.has_key(name):
                            classes.write("        %s\n" %
                                          (function_post[name]));

1523 1524 1525
                        classes.write("        return ");
                        classes.write(converter_type[ret[0]] % ("ret"));
                        classes.write("\n");
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539

                    # For functions returning an integral type there
                    # are several things that we can do, depending on
                    # the contents of functions_int_*:
                    elif is_integral_type (ret[0]):
                        if not functions_noexcept.has_key (name):
                            if functions_int_exception_test.has_key (name):
                                test = functions_int_exception_test[name]
                            else:
                                test = functions_int_default_test
                            if classname == "virConnect":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', conn=self)\n") %
                                               ("ret", name))
1540 1541 1542 1543 1544 1545 1546 1547
                            elif classname == "virDomain":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', dom=self)\n") %
                                               ("ret", name))
                            elif classname == "virNetwork":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', net=self)\n") %
                                               ("ret", name))
1548 1549 1550 1551
                            elif classname == "virInterface":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', net=self)\n") %
                                               ("ret", name))
1552 1553 1554 1555 1556 1557 1558 1559
                            elif classname == "virStoragePool":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', pool=self)\n") %
                                               ("ret", name))
                            elif classname == "virStorageVol":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', vol=self)\n") %
                                               ("ret", name))
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
                            else:
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed')\n") %
                                               ("ret", name))

                        # Post-processing - just before we return.
                        if function_post.has_key(name):
                            classes.write("        %s\n" %
                                          (function_post[name]));

                        classes.write ("        return ret\n")

                    elif is_list_type (ret[0]):
                        if not functions_noexcept.has_key (name):
                            if functions_list_exception_test.has_key (name):
                                test = functions_list_exception_test[name]
                            else:
                                test = functions_list_default_test
                            if classname == "virConnect":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', conn=self)\n") %
                                               ("ret", name))
1582 1583 1584 1585 1586 1587 1588 1589
                            elif classname == "virDomain":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', dom=self)\n") %
                                               ("ret", name))
                            elif classname == "virNetwork":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', net=self)\n") %
                                               ("ret", name))
1590 1591 1592 1593
                            elif classname == "virInterface":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', net=self)\n") %
                                               ("ret", name))
1594 1595 1596 1597 1598 1599 1600 1601
                            elif classname == "virStoragePool":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', pool=self)\n") %
                                               ("ret", name))
                            elif classname == "virStorageVol":
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed', vol=self)\n") %
                                               ("ret", name))
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
                            else:
                                classes.write (("        if " + test +
                                                ": raise libvirtError ('%s() failed')\n") %
                                               ("ret", name))

                        # Post-processing - just before we return.
                        if function_post.has_key(name):
                            classes.write("        %s\n" %
                                          (function_post[name]));

                        classes.write ("        return ret\n")

1614
                    else:
1615 1616 1617 1618 1619
                        # Post-processing - just before we return.
                        if function_post.has_key(name):
                            classes.write("        %s\n" %
                                          (function_post[name]));

1620
                        classes.write("        return ret\n");
1621

1622
                classes.write("\n");
1623 1624
            # Append "<classname>.py" to class def, iff it exists
            try:
1625
                extra = open(os.path.join(srcPref,"libvirt-override-" + classname + ".py"), "r")
1626 1627 1628 1629
                classes.write ("    #\n")
                classes.write ("    # %s methods from %s.py (hand coded)\n" % (classname,classname))
                classes.write ("    #\n")
                classes.writelines(extra.readlines())
1630
                classes.write("\n")
1631 1632 1633
                extra.close()
            except:
                pass
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647

    #
    # Generate enum constants
    #
    for type,enum in enums.items():
        classes.write("# %s\n" % type)
        items = enum.items()
        items.sort(lambda i1,i2: cmp(long(i1[1]),long(i2[1])))
        for name,value in items:
            classes.write("%s = %s\n" % (name,value))
        classes.write("\n");

    classes.close()

1648 1649 1650 1651 1652 1653 1654
def qemuBuildWrappers(module):
    global qemu_functions

    if not module == "libvirt-qemu":
        print "ERROR: only libvirt-qemu is supported"
        return None

1655
    extra_file = os.path.join(srcPref, "%s-override.py" % module)
1656 1657 1658 1659 1660
    extra = None

    fd = open("libvirt_qemu.py", "w")

    if os.path.exists(extra_file):
1661
        extra = open(extra_file, "r")
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
    fd.write("#! " + python + " -i\n")
    fd.write("#\n")
    fd.write("# WARNING WARNING WARNING WARNING\n")
    fd.write("#\n")
    fd.write("# This file is automatically written by generator.py. Any changes\n")
    fd.write("# made here will be lost.\n")
    fd.write("#\n")
    fd.write("# To change the manually written methods edit " + module + "-override.py\n")
    fd.write("# To change the automatically written methods edit generator.py\n")
    fd.write("#\n")
    fd.write("# WARNING WARNING WARNING WARNING\n")
    fd.write("#\n")
    if extra != None:
        fd.writelines(extra.readlines())
    fd.write("#\n")
    fd.write("# WARNING WARNING WARNING WARNING\n")
    fd.write("#\n")
    fd.write("# Automatically written part of python bindings for libvirt\n")
    fd.write("#\n")
    fd.write("# WARNING WARNING WARNING WARNING\n")
    if extra != None:
        extra.close()

    fd.write("try:\n")
    fd.write("    import libvirtmod_qemu\n")
    fd.write("except ImportError, lib_e:\n")
    fd.write("    try:\n")
    fd.write("        import cygvirtmod_qemu as libvirtmod_qemu\n")
    fd.write("    except ImportError, cyg_e:\n")
    fd.write("        if str(cyg_e).count(\"No module named\"):\n")
    fd.write("            raise lib_e\n\n")

    fd.write("import libvirt\n\n");
    fd.write("#\n# Functions from module %s\n#\n\n" % module)
    #
    # Generate functions directly, no classes
    #
    for name in qemu_functions.keys():
        func = nameFixup(name, 'None', None, None)
        (desc, ret, args, file, mod, cond) = qemu_functions[name]
        fd.write("def %s(" % func)
        n = 0
        for arg in args:
            if n != 0:
                fd.write(", ")
            fd.write("%s" % arg[0])
            n = n + 1
        fd.write("):\n")
        writeDoc(module, name, args, '    ', fd);

        if ret[0] != "void":
            fd.write("    ret = ");
        else:
            fd.write("    ");
        fd.write("libvirtmod_qemu.%s(" % name)
        n = 0

        conn = None

        for arg in args:
            if arg[1] == "virConnectPtr":
                conn = arg[0]

            if n != 0:
                fd.write(", ");
            if arg[1] in ["virDomainPtr", "virConnectPtr"]:
                # FIXME: This might have problem if the function
                # has multiple args which are objects.
                fd.write("%s.%s" % (arg[0], "_o"))
            else:
                fd.write("%s" % arg[0])
            n = n + 1
        fd.write(")\n");

        if ret[0] != "void":
            fd.write("    if ret is None: raise libvirt.libvirtError('" + name + "() failed')\n")
            if ret[0] == "virDomainPtr":
                fd.write("    __tmp = virDomain(" + conn + ",_obj=ret)\n")
                fd.write("    return __tmp\n")
            else:
                fd.write("    return ret\n")

        fd.write("\n")

    #
    # Generate enum constants
    #
    for type,enum in qemu_enums.items():
        fd.write("# %s\n" % type)
        items = enum.items()
        items.sort(lambda i1,i2: cmp(long(i1[1]),long(i2[1])))
        for name,value in items:
            fd.write("%s = %s\n" % (name,value))
        fd.write("\n");

    fd.close()


quiet = 0
if buildStubs("libvirt") < 0:
    sys.exit(1)
if buildStubs("libvirt-qemu") < 0:
1764
    sys.exit(1)
1765 1766
buildWrappers("libvirt")
qemuBuildWrappers("libvirt-qemu")
1767
sys.exit(0)