Example #1
0
def qemuMonitorEventRegister(conn: libvirt.virConnect,
                             dom: libvirt.virDomain,
                             event: str,
                             cb: Callable[[
                                 libvirt.virConnect, libvirt.
                                 virDomain, str, int, int, str, libvirt._T
                             ], None],
                             opaque: libvirt._T,
                             flags: int = 0) -> int:
    """Adds a qemu monitor event callback. Registering for a monitor
       callback will enable delivery of the events"""
    if not hasattr(conn, 'qemuMonitorEventCallbackID'):
        conn.qemuMonitorEventCallbackID = {}  # type: ignore
    cbData = {"cb": cb, "conn": conn, "opaque": opaque}
    if dom is None:
        ret = libvirtmod_qemu.virConnectDomainQemuMonitorEventRegister(
            conn._o, None, event, cbData, flags)
    else:
        ret = libvirtmod_qemu.virConnectDomainQemuMonitorEventRegister(
            conn._o, dom._o, event, cbData, flags)
    if ret == -1:
        raise libvirt.libvirtError(
            'virConnectDomainQemuMonitorEventRegister() failed')
    conn.qemuMonitorEventCallbackID[ret] = opaque  # type: ignore
    return ret
Example #2
0
def createMachine(virt_conn: libvirt.virConnect, xml: str) -> bool:
    """ Create VM """

    virt_conn = reassureConnection(virt_conn)

    try:
        virt_conn.defineXML(xml)
    except libvirt.libvirtError:
        return False

    return True
Example #3
0
def checkIfNetworkExists(virt_conn: libvirt.virConnect,
                         network_name: str) -> bool:
    """ Check if network exists """

    virt_conn = reassureConnection(virt_conn)

    try:
        virt_conn.networkLookupByName(network_name)
    except libvirt.libvirtError:
        return False

    return True
Example #4
0
def reassureConnection(virt_conn: libvirt.virConnect) -> libvirt.virConnect:
    """ Check libvirt connection. Reconnect if needed """

    if not isinstance(virt_conn, libvirt.virConnect):
        raise Exception("libvirt.virConnect type expected in virt_conn")

    if not virt_conn.isAlive():
        URI = virt_conn.getURI()

        del virt_conn
        virt_conn = libvirt.open(URI)

    if virt_conn.isAlive():
        return virt_conn
    else:
        raise Exception(
            f"Was unable to connect to the libvirt daemon under {URI}")
Example #5
0
    def __init__(self, conn: libvirt.virConnect, domain_name: str):
        self.dom = None

        try:
            self.dom = conn.lookupByName(domain_name)
            self.block = Block(self.dom)
        except Exception as e:
            print("makine bulunamadi, makineyi kontrol ediniz...", str(e.args))
            exit(1)
Example #6
0
def listMachines(virt_conn: libvirt.virConnect) -> list:
    """ Return a list of machines and states
    Returns a list with:
    * a string with the machine name
    * a boolean with machine state
"""

    virt_conn = reassureConnection(virt_conn)

    all_domains = {x.name(): x.state()[0] for x in virt_conn.listAllDomains()}

    return all_domains
Example #7
0
def _machineOperation(virt_conn: libvirt.virConnect,
                      domain_name: str,
                      operation: str,
                      force: bool = False) -> [int, bool]:
    """ Do not export/import this function """

    try:
        vm = virt_conn.lookupByName(domain_name)
    except libvirt.libvirtError:
        raise Exception("No VM found with the provided name")

    ops = {
        'stop': {
            'function': vm.shutdown,
            'state_list': [MACHINE_STATE_SHUTDOWN, MACHINE_STATE_SHUTOFF],
        },
        'start': {
            'function': vm.create,
            'state_list': [
                MACHINE_STATE_RUNNING,
            ],
        },
    }

    if operation == "stop" and force:
        ops['stop']['function'] = vm.destroy

    if operation not in ops.keys():
        raise Exception(
            f"Unknown operation. Available operations: {ops.keys()}")

    state = vm.state()[0]

    if state not in ops[operation]['state_list']:

        _ = ops[operation]['function']()
        sleep(1)
        new_state = vm.state()[0]

        if new_state not in ops[operation]['state_list']:
            sleep(5)
            new_state = vm.state()[0]
            if new_state not in ops[operation]['state_list']:
                raise Exception(
                    f"VM refused to perform the {operation} action")
        return [new_state, False]

    elif state in ops[operation]['state_list']:
        # Machine was already in state
        return [state, True]

    raise Exception("VM is blocked")
Example #8
0
def deleteNetwork(virt_conn: libvirt.virConnect, network_name: str) -> bool:
    """ Undefine and destroy a network """

    virt_conn = reassureConnection(virt_conn)

    try:
        network = virt_conn.networkLookupByName(network_name)
    except libvirt.libvirtError:
        return False

    network.destroy()
    network.undefine()

    return True
Example #9
0
def createNetwork(virt_conn: libvirt.virConnect, xml: str) -> bool:
    """ Define and start a network """

    virt_conn = reassureConnection(virt_conn)

    try:
        network = virt_conn.networkDefineXML(xml)
    except libvirt.libvirtError:
        return False

    network.setAutostart(True)
    network.create()

    return True
Example #10
0
def machineStopped(virt_conn: libvirt.virConnect, domain_name: str):

    virt_conn = reassureConnection(virt_conn)

    try:
        vm = virt_conn.lookupByName(domain_name)
    except libvirt.libvirtError:
        raise Exception("No VM found with the provided name")

    state = vm.state()[0]

    if state in [MACHINE_STATE_SHUTDOWN, MACHINE_STATE_SHUTOFF]:
        return True
    else:
        return False
Example #11
0
def getDomainDisks(conn: libvirt.virConnect, dom: libvirt.virDomain):
    stats = conn.domainListGetStats([dom], libvirt.VIR_DOMAIN_STATS_BLOCK , libvirt.VIR_CONNECT_GET_ALL_DOMAINS_STATS_BACKING)[0][1]
    result = dict()
    for i in range(0, stats['block.count']):
        name = stats['block.' + str(i) + '.name']
        path = stats.get('block.' + str(i) + '.path', None)
        backing_index = stats.get('block.' + str(i) + '.backingIndex', 0)
        if not path:
            # Ignore non disks
            continue
        if not name in result:
            result[name] = dict()
            result[name]["name"] = name
            result[name]["files"] = dict()
        result[name]["files"][backing_index] = path
    return result
Example #12
0
def revertSnapshot(virt_conn: libvirt.virConnect, domain_name: str,
                   snapshot_name: str) -> bool:
    """ Revert a snapshot of shutoff VM """

    virt_conn = reassureConnection(virt_conn)

    vm = virt_conn.lookupByName(domain_name)
    snapshot = vm.snapshotLookupByName(snapshot_name)

    # Make sure VM is shutoff
    _, _ = stopMachine(virt_conn, domain_name)

    try:
        vm.revertToSnapshot(snapshot)
    except libvirt.libvirtError:
        return False

    return True
Example #13
0
def createSnapshot(virt_conn: libvirt.virConnect, domain_name: str,
                   snapshot_name: str) -> bool:
    """ Make a snapshot of shutoff VM """

    virt_conn = reassureConnection(virt_conn)

    # Make sure VM is shutoff
    _, _ = stopMachine(virt_conn, domain_name)

    vm = virt_conn.lookupByName(domain_name)

    try:
        vm.snapshotCreateXML(
            SNAPSHOT_XML_TEMPLATE.format(snapshot_name=snapshot_name))
    except libvirt.libvirtError:
        return False

    return True
Example #14
0
def addOrUpdateHost(virt_conn: libvirt.virConnect, network_name: str, mac: str,
                    ip: str) -> bool:
    """ Add or update host static IP assignment in DHCP server

This definition is taken from otherwiseguy repo from github:
https://github.com/otherwiseguy/virt-add-static-dhcp
Adjusted to this repo needs
"""
    virt_conn = reassureConnection(virt_conn)

    virt_network = virt_conn.networkLookupByName(network_name)

    cmd = libvirt.VIR_NETWORK_UPDATE_COMMAND_MODIFY
    section = libvirt.VIR_NETWORK_SECTION_IP_DHCP_HOST
    xml = "<host mac='%s' ip='%s'/>" % (mac, ip)
    flags = (libvirt.VIR_NETWORK_UPDATE_AFFECT_LIVE
             | libvirt.VIR_NETWORK_UPDATE_AFFECT_CONFIG)
    try:
        virt_network.update(cmd, section, -1, xml, flags)
    except:
        cmd = libvirt.VIR_NETWORK_UPDATE_COMMAND_ADD_FIRST
        virt_network.update(cmd, section, -1, xml, flags)

    return True
Example #15
0
def myConnectionCloseCallback(conn: libvirt.virConnect, reason: int, opaque: _T) -> None:
    print("myConnectionCloseCallback: %s: %s" % (
        conn.getURI(), CONNECTION_EVENTS[reason]))
    global run
    run = False
Example #16
0
def listNetworks(virt_conn: libvirt.virConnect) -> list:
    """ Return list of libvirt.virNetwork objects """

    virt_conn = reassureConnection(virt_conn)

    return virt_conn.listAllNetworks()