define-alpine-the-sequel/qemu.ts

91 lines
2.5 KiB
TypeScript
Raw Normal View History

import { cp, mkdir, mkdtemp, rm } from "node:fs/promises";
2023-02-02 21:25:11 +00:00
import { tmpdir } from "node:os";
import path, { join } from "node:path";
2023-02-22 23:09:07 +00:00
import { canAccess, execFile } from "./helpers/better-api.js";
2023-02-21 16:19:57 +00:00
import { sudoChownToRunningUser } from "./helpers/sudo.js";
2023-02-02 21:25:11 +00:00
export async function runQemu(
squashfs: string,
2023-02-19 20:58:18 +00:00
kernel: { initramfs: string; vmlinuz: string },
2023-02-02 21:59:13 +00:00
{ graphic, noShutdown }: { graphic?: boolean; noShutdown?: boolean } = {
2023-02-02 21:55:18 +00:00
graphic: true,
noShutdown: false,
}
2023-02-02 21:25:11 +00:00
) {
2023-02-21 16:19:57 +00:00
await sudoChownToRunningUser(kernel.initramfs);
await sudoChownToRunningUser(kernel.vmlinuz);
await sudoChownToRunningUser(squashfs);
2023-02-02 21:25:11 +00:00
const tmp = await mkdtemp(path.join(tmpdir(), "define-alpine-qemu-"));
try {
2023-02-22 23:09:07 +00:00
// const disk = path.join(tmp, "tmp.ext4");
const disk = "tmp.ext4";
if (!(await canAccess(disk))) {
await execFile("fallocate", ["--length", "1G", disk]);
await execFile("mkfs.ext4", ["-F", disk]);
}
{
const mountpoint = join(tmp, "persist-mount");
await mkdir(mountpoint);
await execFile("sudo", ["mount", disk, mountpoint]);
try {
await execFile("sudo", [
"cp",
squashfs,
join(mountpoint, "current.squashfs"),
]);
} finally {
await execFile("sudo", ["umount", mountpoint]);
}
}
2023-02-02 21:25:11 +00:00
let kernelAppend = [
"root=/dev/sda",
"rootfstype=ext4",
2023-02-02 21:25:11 +00:00
"modules=ext4",
"quiet",
"init=/sbin/runit-init",
];
let qemuAppend: string[] = [];
if (!graphic) {
kernelAppend.push("console=ttyS0");
qemuAppend.push("-nographic");
}
2023-02-02 21:55:18 +00:00
if (noShutdown) qemuAppend.push("-no-shutdown");
2023-02-02 21:25:11 +00:00
// sudo chown root:$(id -u) -R boot/ && sudo chmod g+rw -R boot/
await execFile("qemu-system-x86_64", [
"-enable-kvm",
"-m",
"2048",
// "-drive",
// `file=${squashfs},media=disk,format=raw`,
2023-02-02 21:25:11 +00:00
"-drive",
`file=${disk},media=disk,format=raw`,
"-net",
"nic,model=virtio-net-pci",
"-net",
"user,hostfwd=tcp:127.0.0.1:8080-:80",
"-kernel",
kernel.vmlinuz,
"-initrd",
kernel.initramfs,
"-append",
kernelAppend.join(" "),
...qemuAppend,
]);
// -append "root=/dev/sda rootfstype=squashfs modules=ext4 quiet init=/sbin/runit-init $append" $qemuappend
} finally {
await rm(tmp, { recursive: true, force: true });
}
}
2023-02-19 20:58:18 +00:00
await runQemu(
"artifacts/image.squashfs",
{
initramfs: "artifacts/kernel/initramfs",
vmlinuz: "artifacts/kernel/vmlinuz",
},
2023-02-22 23:09:07 +00:00
{ graphic: true, noShutdown: true }
2023-02-19 20:58:18 +00:00
);