libvirt+pythonで仮想マシンのリソース消費情報を取得する

creation date 2016/10/06 01:34 last date modified 2016/11/22 00:55 | category: | tags: Python
スポンサード リンク

libvirtを使ってpythonからホストとkmvのドメイン情報を取得するスクリプトを作成した。 書きかけだが,ここにメモしておく。

import sys
import libvirt



def host_info(conn):
    nodeinfo = conn.getInfo()
    host_dict = {'Hostname': conn.getHostname(),
                 'Maximum_support_virtual_CPUs': conn.getMaxVcpus(None),
                 'Model': nodeinfo[0],
                 'Max_Memory_size_in_MB': nodeinfo[1],
                 'Number_of_CPUs': nodeinfo[2],
                 'MHz_of_CPUs': nodeinfo[3],
                 'Number_of_CPU_sockets': nodeinfo[5],
                 'Number_of_CPU_cores_per_socket': nodeinfo[6],
                 'Number_of_CPU_threads_per_core': nodeinfo[7],
                 'Free_Memory_in_bytes': conn.getFreeMemory()}

    stats = conn.getCPUStats(libvirt.VIR_NODE_CPU_STATS_ALL_CPUS)
    host_dict['CPU_Kernel_time_in_ns'] = stats['kernel']
    host_dict['CPU_Idle_time_in_ns'] = stats['idle']
    host_dict['CPU_User_time_in_ns'] = stats['user']
    host_dict['CPU_Iowait_time_in_ns'] = stats['iowait']
    for x in range(host_dict['Number_of_CPUs']):
        stats = conn.getCPUStats(x)
        host_dict['CPU' + str(x) + '_Kernel_time_in_ns'] = stats['kernel']
        host_dict['CPU' + str(x) + '_Idle_time_in_ns'] = stats['idle']
        host_dict['CPU' + str(x) + '_User_time_in_ns'] = stats['user']
        host_dict['CPU' + str(x) + '_Iowait_time_in_ns'] = stats['iowait']

    return host_dict


def domain_status(conn):
    # loop for all domains
    domains = conn.listAllDomains(0)
    if len(domains) != 0:
        domain_dicts = []
        for domain in domains:
            domain_dict = {'Domain_Hostname': dom.hostname(),
                           'Domain_OS_Type': dom.OSType(),
                           'Domain_UUID': dom.UUIDString(),
                           'Domain_ID': dom.ID(),
                           'Domain_Max_Memory_size_in_MB': dom.maxMemory(),
                           'Domain_Max_Number_of_vCPUs': dom.maxVcpus(),
                           'Domain_Time': dom.getTime()}
            # struct = dom.getTime()
            # timestamp = time.ctime(float(struct['seconds']))
            # dom.getCPUStats(False)
            # dom.memoryStats()
            state, reason = dom.state()
            if state == libvirt.VIR_DOMAIN_NOSTATE:
                domain_dict.update({'Domain_State': 'nostate'})
            elif state == libvirt.VIR_DOMAIN_RUNNING:
                domain_dict.update({'Domain_State': 'running'})
            elif state == libvirt.VIR_DOMAIN_BLOCKED:
                domain_dict.update({'Domain_State': 'blocked'})
            elif state == libvirt.VIR_DOMAIN_PAUSED:
                domain_dict.update({'Domain_State': 'paused'})
            elif state == libvirt.VIR_DOMAIN_SHUTDOWN:
                domain_dict.update({'Domain_State': 'shutdown'})
            elif state == libvirt.VIR_DOMAIN_SHUTOFF:
                domain_dict.update({'Domain_State': 'shutoff'})
            elif state == libvirt.VIR_DOMAIN_CRASHED:
                domain_dict.update({'Domain_State': 'crashed'})
            elif state == libvirt.VIR_DOMAIN_PMSUSPENDED:
                domain_dict.update({'Domain_State': 'pmsuspended'})
            else:
                domain_dict.update({'Domain_State': 'unknown'})
            domain_dict.update({'Domain_State_Reason_Code': reason})
            domain_dicts.append(domain_dict)
    return domain_dicts


def aggregate_domains(domain_dicts):
    states = [x['state'] for x in domain_dicts]
    agregate_dict = {'Number_of_Domains': len(domain_dicts),
                     'Number_of_Nostate_Domains': states.count('nostate'),
                     'Number_of_Running_Domains': states.count('running'),
                     'Number_of_Blocked_Domains': states.count('blocked'),
                     'Number_of_Paused_Domains': states.count('paused'),
                     'Number_of_Shutdown_Domains': states.count('shutdown'),
                     'Number_of_Shutoff_Domains': states.count('shutoff'),
                     'Number_of_Crashed_Domains': states.count('crashed'),
                     'Number_of_Pmsuspended_Domains': states.count('pmsuspended'),
                     'Number_of_Unknown_Domains': states.count('unknown'),
                     'Domain_UUIDs': [x['Domain_UUID'] for x in domain_dicts]}
    return aggregate_dict


conn = libvirt.open('qemu:///system')
if conn is None:
    print 'Failed to open connection to qemu:///system'
    exit(1)

host_dict = host_info(conn)
instance_dicts = domain_status(conn)
instance_dicts.update(domain_status(instance_dicts))
instance_dicts.update(read_libvirtxml(instance_dicts))

conn.close()
exit(0)

Comments !

social