⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xapi.py

📁 xen虚拟机源代码安装包
💻 PY
📖 第 1 页 / 共 2 页
字号:
    opts, args = parse_args('vbd-create', args)    if len(args) < 2:        raise OptionError("Configuration file and domain not specified")    domname = args[0]    if len(args) > 1:        filename = args[1]        cfg = _read_python_cfg(filename)    else:        cfg = {}            for opt, val in opts:        cfg[opt] = val        print 'Creating VBD ...',    server, session = connect()    vm_uuid = resolve_vm(server, session, domname)    cfg['VM'] = vm_uuid    vbd_uuid = execute(server, 'VBD.create', (session, cfg), async = async)    if async:        print 'Task started: %s' % vbd_uuid    else:        print 'Done. (%s)' % vbd_uuiddef xapi_vif_create(args, async = False):    if len(args) < 2:        raise OptionError("Configuration file not specified")    domname = args[0]    filename = args[1]    cfg = _read_python_cfg(filename)        print 'Creating VIF from %s ..' % filename    server, session = connect()    vm_uuid = resolve_vm(server, session, domname)    cfg['VM'] = vm_uuid    vif_uuid = execute(server, 'VIF.create', (session, cfg), async = async)    if async:        print 'Task started: %s' % vif_uuid    else:        print 'Done. (%s)' % vif_uuiddef xapi_vbd_list(args, async = False):    server, session = connect()    domname = args[0]        dom_uuid = resolve_vm(server, session, domname)    vbds = execute(server, 'VM.get_VBDs', (session, dom_uuid))        print VBD_LIST_FORMAT % {'device': 'Device',                             'uuid' : 'UUID',                             'VDI': 'VDI'}        for vbd in vbds:        vbd_struct = execute(server, 'VBD.get_record', (session, vbd))        print VBD_LIST_FORMAT % vbd_struct                def xapi_vbd_stats(args, async = False):    server, session = connect()    domname = args[0]    dom_uuid = resolve_vm(server, session, domname)    vbds = execute(server, 'VM.get_VBDs', (session, dom_uuid))    for vbd_uuid in vbds:        print execute(server, 'VBD.get_io_read_kbs', (session, vbd_uuid)) def xapi_vif_list(args, async = False):    server, session = connect()    opts, args = parse_args('vdi-list', args, set_defaults = True)    is_long = opts and opts.long        domname = args[0]        dom_uuid = resolve_vm(server, session, domname)    vifs = execute(server, 'VM.get_VIFs', (session, dom_uuid))    if not is_long:        print VIF_LIST_FORMAT % {'name': 'Name',                                 'device': 'Device',                                 'uuid' : 'UUID',                                 'MAC': 'MAC'}                for vif in vifs:            vif_struct = execute(server, 'VIF.get_record', (session, vif))            print VIF_LIST_FORMAT % vif_struct    else:        for vif in vifs:            vif_struct = execute(server, 'VIF.get_record', (session, vif))            pprint(vif_struct)def xapi_console_list(args, async = False):    server, session = connect()    opts, args = parse_args('vdi-list', args, set_defaults = True)    is_long = opts and opts.long        domname = args[0]        dom_uuid = resolve_vm(server, session, domname)    consoles = execute(server, 'VM.get_consoles', (session, dom_uuid))    if not is_long:        print CONSOLE_LIST_FORMAT % {'protocol': 'Protocol',                                     'location': 'Location',                                     'uuid': 'UUID'}        for console in consoles:            console_struct = execute(server, 'console.get_record',                                     (session, console))            print CONSOLE_LIST_FORMAT % console_struct    else:        for console in consoles:            console_struct = execute(server, 'console.get_record',                                     (session, console))            pprint(console_struct)            def xapi_vdi_list(args, async = False):    opts, args = parse_args('vdi-list', args, set_defaults = True)    is_long = opts and opts.long    server, session = connect()    vdis = execute(server, 'VDI.get_all', (session,))    if not is_long:        print VDI_LIST_FORMAT % {'name_label': 'VDI Label',                                 'uuid' : 'UUID',                                 'virtual_size': 'Bytes'}                for vdi in vdis:            vdi_struct = execute(server, 'VDI.get_record', (session, vdi))            print VDI_LIST_FORMAT % vdi_struct    else:        for vdi in vdis:            vdi_struct = execute(server, 'VDI.get_record', (session, vdi))            pprint(vdi_struct)def xapi_sr_list(args, async = False):    opts, args = parse_args('sr-list', args, set_defaults = True)    is_long = opts and opts.long        server, session = connect()    srs = execute(server, 'SR.get_all', (session,))    if not is_long:        print SR_LIST_FORMAT % {'name_label': 'SR Label',                                'uuid' : 'UUID',                                'physical_size': 'Size (MB)',                                'type': 'Type'}                for sr in srs:            sr_struct = execute(server, 'SR.get_record', (session, sr))            sr_struct['physical_size'] = int(sr_struct['physical_size'])/MB            print SR_LIST_FORMAT % sr_struct    else:        for sr in srs:            sr_struct = execute(server, 'SR.get_record', (session, sr))              pprint(sr_struct)def xapi_sr_rename(args, async = False):    server, session = connect()    sr = execute(server, 'SR.get_by_name_label', (session, args[0]))    execute(server, 'SR.set_name_label', (session, sr[0], args[1]))def xapi_vdi_create(args, async = False):    opts, args = parse_args('vdi-create', args)    if len(args) > 0:        cfg = _read_python_cfg(args[0])    else:        cfg = {}            for opt, val in opts:        cfg[opt] = val    server, session = connect()    srs = []    if cfg.get('SR'):            srs = execute(server, 'SR.get_by_name_label', (session, cfg['SR']))    else:        srs = execute(server, 'SR.get_all', (session,))    sr = srs[0]    cfg['SR'] = sr    size = cfg['virtual_size']/MB    print 'Creating VDI of size: %dMB ..' % size,    uuid = execute(server, 'VDI.create', (session, cfg), async = async)    if async:        print 'Task started: %s' % uuid    else:        print 'Done. (%s)' % uuid    def xapi_vdi_destroy(args, async = False):    server, session = connect()    if len(args) < 1:        raise OptionError('Not enough arguments')    vdi_uuid = args[0]    print 'Deleting VDI %s' % vdi_uuid    result = execute(server, 'VDI.destroy', (session, vdi_uuid), async = async)    if async:        print 'Task started: %s' % result    else:        print 'Done.'def xapi_vdi_rename(args, async = False):    server, session = connect()    if len(args) < 2:        raise OptionError('Not enough arguments')    vdi_uuid = execute(server, 'VDI.get_by_name_label', session, args[0])    vdi_name = args[1]        print 'Renaming VDI %s to %s' % (vdi_uuid[0], vdi_name)    result = execute(server, 'VDI.set_name_label',                     (session, vdi_uuid[0], vdi_name), async = async)    if async:        print 'Task started: %s' % result    else:        print 'Done.'def xapi_vtpm_create(args, async = False):    server, session = connect()    domname = args[0]    cfg = _read_python_cfg(args[1])    vm_uuid = resolve_vm(server, session, domname)    cfg['VM'] = vm_uuid    print "Creating vTPM with cfg = %s" % cfg    vtpm_uuid = execute(server, 'VTPM.create', (session, cfg))    print "Done. (%s)" % vtpm_uuiddef xapi_pif_list(args, async = False):    server, session = connect()    pif_uuids = execute(server, 'PIF.get_all', (session,))    for pif_uuid in pif_uuids:        pif = execute(server, 'PIF.get_record', (session, pif_uuid))        print pifdef xapi_debug_wait(args, async = False):    secs = 10    if len(args) > 0:        secs = int(args[0])    server, session = connect()    task_uuid = execute(server, 'debug.wait', (session, secs), async=async)    print 'Task UUID: %s' % task_uuiddef xapi_vm_stat(args, async = False):    domname = args[0]        server, session = connect()    vm_uuid = resolve_vm(server, session, domname)    vif_uuids = execute(server, 'VM.get_VIFs', (session, vm_uuid))    vbd_uuids = execute(server, 'VM.get_VBDs', (session, vm_uuid))    vcpus_utils = execute(server, 'VM.get_VCPUs_utilisation',                          (session, vm_uuid))    for vcpu_num in sorted(vcpus_utils.keys()):        print 'CPU %s : %5.2f%%' % (vcpu_num, vcpus_utils[vcpu_num] * 100)            for vif_uuid in vif_uuids:        vif = execute(server, 'VIF.get_record', (session, vif_uuid))        print '%(device)s: rx: %(io_read_kbs)10.2f tx: %(io_write_kbs)10.2f' \              % vif    for vbd_uuid in vbd_uuids:        vbd = execute(server, 'VBD.get_record', (session, vbd_uuid))        print '%(device)s: rd: %(io_read_kbs)10.2f wr: %(io_write_kbs)10.2f' \              % vbd        ## Command Line Utils#import cmdimport shlexclass XenAPICmd(cmd.Cmd):    def __init__(self, server, session):        cmd.Cmd.__init__(self)        self.server = server        self.session = session        self.prompt = ">>> "    def default(self, line):        words = shlex.split(line)        if len(words) > 0:            cmd_name = words[0].replace('-', '_')            is_async = 'async' in cmd_name            if is_async:                cmd_name = re.sub('async_', '', cmd_name)                            func_name = 'xapi_%s' % cmd_name            func = globals().get(func_name)                        if func:                try:                    args = tuple(words[1:])                    func(args, async = is_async)                    return True                except SystemExit:                    return False                except OptionError, e:                    print 'Error:', str(e)                    return False                except Exception, e:                    import traceback                    traceback.print_exc()                    return False        print '*** Unknown command: %s' % words[0]        return False    def do_EOF(self, line):        print        sys.exit(0)    def do_help(self, line):        usage(print_usage = False)    def emptyline(self):        pass    def postcmd(self, stop, line):        return False    def precmd(self, line):        words = shlex.split(line)        if len(words) > 0:            words0 = words[0].replace('-', '_')            return ' '.join([words0] + words[1:])        else:            return linedef shell():    server, session = connect()    x = XenAPICmd(server, session)    x.cmdloop('Xen API Prompt. Type "help" for a list of functions')def usage(command = None, print_usage = True):    if not command:        if print_usage:            print 'Usage: xapi <subcommand> [options] [args]'            print            print 'Subcommands:'            print        for func in sorted(globals().keys()):            if func.startswith('xapi_'):                command = func[5:].replace('_', '-')                args, description = COMMANDS.get(command, ('', ''))                print '%-16s  %-40s' % (command, description)        print    else:        parse_args(command, ['-h'])def main(args):        # poor man's optparse that doesn't abort on unrecognised opts    options = {}    remaining = []        arg_n = 0    while args:        arg = args.pop(0)                if arg in ('--help', '-h'):            options['help'] = True        elif arg in ('--server', '-s') and args:            options['server'] = args.pop(0)        elif arg in ('--user', '-u') and args:            options['user'] = args.pop(0)        elif arg in ('--password', '-p') and args:            options['password'] = args.pop(0)        else:            remaining.append(arg)    # abort here if these conditions are true    if options.get('help') and not remaining:        usage()        sys.exit(1)    if options.get('help') and remaining:        usage(remaining[0])        sys.exit(1)    if not remaining:        usage()        sys.exit(1)    if options.get('server'):        # it is ugly to use a global, but it is simple        global SERVER_URI        SERVER_URI = options['server']    if options.get('user'):        global SERVER_USER        SERVER_USER = options['user']    if options.get('password'):        global SERVER_PASS        SERVER_PASS = options['password']    subcmd = remaining[0].replace('-', '_')    is_async = 'async' in subcmd    if is_async:        subcmd = re.sub('async_', '', subcmd)    subcmd_func_name = 'xapi_' + subcmd    subcmd_func = globals().get(subcmd_func_name, None)    if subcmd == 'shell':        shell()    elif not subcmd_func or not callable(subcmd_func):        print 'Error: Unable to find subcommand \'%s\'' % subcmd        usage()        sys.exit(1)    try:        subcmd_func(remaining[1:], async = is_async)    except XenAPIError, e:        print 'Error: %s' % str(e.args[0])        sys.exit(2)    except OptionError, e:        print 'Error: %s' % e    sys.exit(0)    if __name__ == "__main__":    import sys    main(sys.argv[1:])

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -