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

📄 main.py

📁 xen虚拟机源代码安装包
💻 PY
📖 第 1 页 / 共 5 页
字号:
                    if domain_names:            doms = [['domain'] + map2sxp(dom) for dom in doms_dict                    if dom["name"] in domain_names]                        if len(doms) > 0:                return doms            else:                print "Error: no domain%s named %s" % \                      (len(domain_names) > 1 and 's' or '',                       ', '.join(domain_names))                sys.exit(-1)        else:            return doms_sxp    else:        if domain_names:            return [server.xend.domain(dom, full) for dom in domain_names]        else:            return server.xend.domains_with_state(True, state, full)def xm_list(args):    use_long = 0    show_vcpus = 0    show_labels = 0    state = 'all'    try:        (options, params) = getopt.gnu_getopt(args, 'lv',                                              ['long','vcpus','label',                                               'state='])    except getopt.GetoptError, opterr:        err(opterr)        usage('list')        for (k, v) in options:        if k in ['-l', '--long']:            use_long = 1        if k in ['-v', '--vcpus']:            show_vcpus = 1        if k in ['--label']:            show_labels = 1        if k in ['--state']:            state = v    if state != 'all' and len(params) > 0:        raise OptionError(            "You may specify either a state or a particular VM, but not both")    if show_vcpus:        print >>sys.stderr, (            "xm list -v is deprecated.  Please use xm vcpu-list.")        xm_vcpu_list(params)        return    doms = getDomains(params, state, use_long)    if use_long:        map(PrettyPrint.prettyprint, doms)    elif show_labels:        xm_label_list(doms)    else:        xm_brief_list(doms)def parse_doms_info(info):    def get_info(n, t, d):        return t(sxp.child_value(info, n, d))    def get_status(n, t, d):        return DOM_STATES[t(sxp.child_value(info, n, d))]    start_time = get_info('start_time', float, -1)    if start_time == -1:        up_time = float(-1)    else:        up_time = time.time() - start_time    parsed_info = {        'domid'    : get_info('domid',              str,   ''),        'name'     : get_info('name',               str,   '??'),        'state'    : get_info('state',              str,   ''),        # VCPUs is the number online when the VM is up, or the number        # configured otherwise.        'vcpus'    : get_info('online_vcpus', int,                              get_info('vcpus', int, 0)),        'up_time'  : up_time        }    security_label = get_info('security_label', str, '')    parsed_info['seclabel'] = security.parse_security_label(security_label)    if serverType == SERVER_XEN_API:        parsed_info['mem'] = get_info('memory_actual', int, 0) / 1024        cpu_times = get_info('cpu_time', lambda x : (x), 0.0)        if sum(cpu_times.values()) > 0:            parsed_info['cpu_time'] = sum(cpu_times.values()) / float(len(cpu_times.values()))        else:            parsed_info['cpu_time'] = 0    else:        parsed_info['mem'] = get_info('memory', int,0)        parsed_info['cpu_time'] = get_info('cpu_time', float, 0.0)    return parsed_infodef check_sched_type(sched):    if serverType == SERVER_XEN_API:        current = server.xenapi.host.get_sched_policy(            server.xenapi.session.get_this_host(server.getSession()))    else:        current = 'unknown'        for x in server.xend.node.info()[1:]:            if len(x) > 1 and x[0] == 'xen_scheduler':                current = x[1]                break    if sched != current:        err("Xen is running with the %s scheduler" % current)        sys.exit(1)def parse_sedf_info(info):    def get_info(n, t, d):        return t(sxp.child_value(info, n, d))    return {        'domid'    : get_info('domid',         int,   -1),        'period'   : get_info('period',        int,   -1),        'slice'    : get_info('slice',         int,   -1),        'latency'  : get_info('latency',       int,   -1),        'extratime': get_info('extratime',     int,   -1),        'weight'   : get_info('weight',        int,   -1),        }def domid_match(domid, info):    return domid is None or domid == info['name'] or \           domid == str(info['domid'])def xm_brief_list(doms):    print '%-40s %5s %5s %5s %10s %9s' % \          ('Name', 'ID', 'Mem', 'VCPUs', 'State', 'Time(s)')        format = "%(name)-40s %(domid)5s %(mem)5d %(vcpus)5d %(state)10s " \             "%(cpu_time)8.1f"        for dom in doms:        d = parse_doms_info(dom)        print format % ddef xm_label_list(doms):    print '%-40s %5s %5s %5s %10s %9s %-10s' % \          ('Name', 'ID', 'Mem', 'VCPUs', 'State', 'Time(s)', 'Label')    output = []    format = '%(name)-40s %(domid)5s %(mem)5d %(vcpus)5d %(state)10s ' \             '%(cpu_time)8.1f %(seclabel)10s'    for dom in doms:        d = parse_doms_info(dom)        if d['seclabel'] == "" and serverType != SERVER_XEN_API:            seclab = server.xend.security.get_domain_label(d['name'])            if len(seclab) > 0 and seclab[0] == '\'':                seclab = seclab[1:]            d['seclabel'] = seclab        output.append((format % d, d['seclabel']))            #sort by labels    output.sort(lambda x,y: cmp( x[1].lower(), y[1].lower()))    for line, label in output:        print linedef xm_vcpu_list(args):    if serverType == SERVER_XEN_API:        if args:            vm_refs = map(get_single_vm, args)        else:            vm_refs = server.xenapi.VM.get_all()                    vm_records = dict(map(lambda vm_ref:                                  (vm_ref, server.xenapi.VM.get_record(                                      vm_ref)),                              vm_refs))        vm_metrics = dict(map(lambda (ref, record):                                  (ref,                                   server.xenapi.VM_metrics.get_record(                                       record['metrics'])),                              vm_records.items()))        dominfo = []        # vcpu_list doesn't list 'managed' domains        # when they are not running, so filter them out        vm_refs = [vm_ref                  for vm_ref in vm_refs                  if vm_records[vm_ref]["power_state"] != "Halted"]        for vm_ref in vm_refs:            info = ['domain',                    ['domid',      vm_records[vm_ref]['domid']],                    ['name',       vm_records[vm_ref]['name_label']],                    ['vcpu_count', vm_records[vm_ref]['VCPUs_max']]]            for i in range(int(vm_records[vm_ref]['VCPUs_max'])):                def chk_flag(flag):                    return flag in vm_metrics[vm_ref]['VCPUs_flags'][str(i)] \                           and 1 or 0                                vcpu_info = ['vcpu',                             ['number',                                  i],                             ['online',                                  chk_flag("online")],                             ['blocked',                                  chk_flag("blocked")],                             ['running',                                  chk_flag("running")],                             ['cpu_time',                                  vm_metrics[vm_ref]['VCPUs_utilisation'][str(i)]],                             ['cpu',                                  vm_metrics[vm_ref]['VCPUs_CPU'][str(i)]],                             ['cpumap',                                  vm_metrics[vm_ref]['VCPUs_params']\                                  ['cpumap%i' % i].split(",")]]                                info.append(vcpu_info)            dominfo.append(info)    else:            if args:            dominfo = map(server.xend.domain.getVCPUInfo, args)        else:            doms = server.xend.domains_with_state(False, 'all', False)            dominfo = map(server.xend.domain.getVCPUInfo, doms)    print '%-32s %5s %5s %5s %5s %9s %s' % \          ('Name', 'ID', 'VCPU', 'CPU', 'State', 'Time(s)', 'CPU Affinity')    format = '%(name)-32s %(domid)5s %(number)5d %(c)5s %(s)5s ' \             ' %(cpu_time)8.1f %(cpumap)s'    for dom in dominfo:        def get_info(n):            return sxp.child_value(dom, n)        #        # convert a list of integers into a list of pairs indicating        # continuous sequences in the list:        #        # [0,1,2,3]   -> [(0,3)]        # [1,2,4,5]   -> [(1,2),(4,5)]        # [0]         -> [(0,0)]        # [0,1,4,6,7] -> [(0,1),(4,4),(6,7)]        #        def list_to_rangepairs(cmap):            cmap.sort()            pairs = []            x = y = 0            for i in range(0,len(cmap)):                try:                    if ((cmap[y+1] - cmap[i]) > 1):                        pairs.append((cmap[x],cmap[y]))                        x = y = i+1                    else:                        y = y + 1                # if we go off the end, then just add x to y                except IndexError:                    pairs.append((cmap[x],cmap[y]))            return pairs        #        # Convert pairs to range string, e.g: [(1,2),(3,3),(5,7)] -> 1-2,3,5-7        #        def format_pairs(pairs):            if not pairs:                return "no cpus"            out = ""            for f,s in pairs:                if (f==s):                    out += '%d'%f                else:                    out += '%d-%d'%(f,s)                out += ','            # trim trailing ','            return out[:-1]        def format_cpumap(cpumap):            cpumap = map(lambda x: int(x), cpumap)            cpumap.sort()            if serverType == SERVER_XEN_API:                nr_cpus = len(server.xenapi.host.get_host_CPUs(                    server.xenapi.session.get_this_host(server.getSession())))            else:                for x in server.xend.node.info()[1:]:                    if len(x) > 1 and x[0] == 'nr_cpus':                        nr_cpus = int(x[1])            # normalize cpumap by modulus nr_cpus, and drop duplicates            cpumap = dict.fromkeys(                       filter(lambda x: x < nr_cpus, cpumap)).keys()            if len(cpumap) == nr_cpus:                return "any cpu"            return format_pairs(list_to_rangepairs(cpumap))        name  = get_info('name')        domid = get_info('domid')        if domid is not None:            domid = str(domid)        else:            domid = ''        for vcpu in sxp.children(dom, 'vcpu'):            def vinfo(n, t):                return t(sxp.child_value(vcpu, n))            number   = vinfo('number',   int)            cpu      = vinfo('cpu',      int)            cpumap   = format_cpumap(vinfo('cpumap', list))            online   = vinfo('online',   int)            cpu_time = vinfo('cpu_time', float)            running  = vinfo('running',  int)            blocked  = vinfo('blocked',  int)            if cpu < 0:                c = ''                s = ''            elif online:                c = str(cpu)                if running:                    s = 'r'                else:                    s = '-'                if blocked:                    s += 'b'                else:                    s += '-'                s += '-'            else:                c = '-'                s = '--p'            print format % locals()def start_do_console(domain_name):    cpid = os.fork()     if cpid != 0:        for i in range(10):            # Catch failure of the create process             time.sleep(1)            (p, rv) = os.waitpid(cpid, os.WNOHANG)            if os.WIFEXITED(rv):                if os.WEXITSTATUS(rv) != 0:                    sys.exit(os.WEXITSTATUS(rv))            try:                # Acquire the console of the created dom                if serverType == SERVER_XEN_API:                    domid = server.xenapi.VM.get_domid(                               get_single_vm(domain_name))                else:                    dom = server.xend.domain(domain_name)                    domid = int(sxp.child_value(dom, 'domid', '-1'))                console.execConsole(domid)            except:                pass        print("Could not start console\n");        sys.exit(0)def xm_start(args):    paused = False    console_autoconnect = False    vncviewer = False    vncviewer_autopass = False    try:        (options, params) = getopt.gnu_getopt(args, 'cp', ['console_autoconnect','paused','vncviewer','vncviewer-autopass'])        for (k, v) in options:            if k in ('-p', '--paused'):                paused = True            if k in ('-c', '--console_autoconnect'):                console_autoconnect = True            if k in ('--vncviewer'):                vncviewer = True            if k in ('--vncviewer-autopass'):                vncviewer_autopass = True        if len(params) != 1:            raise OptionError("Expects 1 argument")    except getopt.GetoptError, opterr:        err(opterr)        usage('start')    dom = params[0]    if console_autoconnect:        start_do_console(dom)    if console_autoconnect:        console.runVncViewer(domid, vncviewer_autopass, True)    try:        if serverType == SERVER_XEN_API:            server.xenapi.VM.start(get_single_vm(dom), paused)            domid = int(server.xenapi.VM.get_domid(get_single_vm(dom)))        else:            server.xend.domain.start(dom, paused)            info = server.xend.domain(dom)            domid = int(sxp.child_value(info, 'domid', '-1'))    except:        raise

⌨️ 快捷键说明

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