Skip to content

Python pinning script

James Le Cuirot edited this page Oct 19, 2024 · 2 revisions

User-contributed script for pinning the processes:

#!/usr/bin/python3

import asyncio
import qemu.qmp
import sys
import subprocess


async def main():
    while True:
        try:
            qmp = qemu.qmp.QMPClient()
            await qmp.connect(sys.argv[1])
            break
        except qemu.qmp.error.QMPError as e:
            print(f"Failed to connect to QEMU: {e}")
            await asyncio.sleep(0.1)

    guest_cpus = await qmp.execute("query-cpus-fast")
    await qmp.disconnect()

    mask = int(sys.argv[2], 16) if len(sys.argv) > 2 else (2 ** len(guest_cpus) - 1)

    guest_cpu = 0
    for host_cpu in range(mask.bit_length()):
        if mask & (1 << host_cpu):
            tid = guest_cpus[guest_cpu]["thread-id"]
            try:
                subprocess.run(["taskset", "-pc", str(host_cpu), str(tid)], check=True)
            except subprocess.CalledProcessError as e:
                print(f"Failed to pin vCPU thread {tid}: {e}")
            guest_cpu += 1


asyncio.run(main())
Clone this wiki locally