opnsense-deps/release/vmhost.sh
Jeremy Karst 1addff9484 build VM: swap disk, small ZFS cache; salvage interrupted ports steps
A 16 GB VM (18 GB in qemu, 7 GB of it ZFS cache) and the HTPC's other
work ran the HTPC out of memory, and its reboot lost 12 hours of the
ports step. The VM now gets a swap disk of its own (swap.qcow2, serial
gwswap, cache=none: off ZFS, where swap can deadlock, and past the
host's page cache), and setup caps the VM's ZFS cache at 2 GB
(vm_memory). The VM itself goes down to 12 GB in vm.conf.

Tools writes the packages set only when a ports step ends. build now
first adds what an interrupted step had finished (salvage_ports): the
runtime packages in the stage's packages directory, when the stage
belongs to the same series, version and ports commit, each checked to
be a whole archive. Build-only dependencies are rebuilt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:50:02 -05:00

198 lines
8.1 KiB
Bash

#!/bin/sh
#
# vmhost.sh: the FreeBSD arm64 build VM, on the host that runs this script. QEMU
# emulates the VM (TCG: any x86_64 or arm64 Linux host, no KVM, no root) inside a
# rootless podman container, so the host needs only podman, curl, sha256sum and xz.
# vm.sh runs this script on the build host over ssh, or here without a build host.
#
# vmhost.sh create OSREL KEYTYPE KEY COMMENT
# download and verify the official FreeBSD OSREL arm64 image,
# grow it, and make the first-boot seed that lets root log in
# with the given ssh public key
# vmhost.sh start OSREL boot the VM; its ssh port is 127.0.0.1:(2200 + OS major)
# vmhost.sh stop OSREL wait for the VM to power off (vm.sh shuts it down first),
# then remove its container
# vmhost.sh status | destroy OSREL
#
# Environment: GW_VMROOT (default ~/gwbuild-vm), GW_VM_CPUS (8), GW_VM_MEM (16G),
# GW_VM_DISK (100G), GW_VM_SWAP (16G, the VM's swap disk).
#
# Copyright 2026 Karst Tech
# SPDX-License-Identifier: BSD-2-Clause
set -eu
VMROOT=${GW_VMROOT:-${HOME}/gwbuild-vm}
CPUS=${GW_VM_CPUS:-8}
MEM=${GW_VM_MEM:-16G}
DISKSIZE=${GW_VM_DISK:-100G}
SWAPSIZE=${GW_VM_SWAP:-16G}
IMAGE=localhost/gwbuild-qemu:1
die()
{
echo "vmhost.sh: $*" >&2
exit 1
}
[ $# -ge 2 ] || die "usage: vmhost.sh create|start|stop|status|destroy OSREL"
CMD=${1}
OSREL=${2}
shift 2
echo "${OSREL}" | grep -Eqx '1[4-9]\.[0-9]' || die "bad FreeBSD release '${OSREL}'"
echo "${CPUS}" | grep -Eqx '[1-9][0-9]{0,2}' || die "bad GW_VM_CPUS '${CPUS}'"
for v in "${MEM}" "${DISKSIZE}" "${SWAPSIZE}"; do
echo "${v}" | grep -Eqx '[1-9][0-9]*[MG]' || die "bad size '${v}'"
done
VMDIR=${VMROOT}/${OSREL}
NAME=gwbuild-${OSREL}
PORT=$((2200 + ${OSREL%.*}))
running()
{
[ "$(podman inspect -f '{{.State.Running}}' "${NAME}" 2>/dev/null)" = true ]
}
# QEMU, its arm64 UEFI firmware and the image tools, from Debian
build_image()
{
podman image exists "${IMAGE}" && return 0
_ctx=$(mktemp -d)
cat > "${_ctx}/Containerfile" <<'EOF'
FROM docker.io/library/debian:trixie-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends qemu-system-arm qemu-efi-aarch64 qemu-utils genisoimage \
&& rm -rf /var/lib/apt/lists/*
EOF
podman build -q -t "${IMAGE}" "${_ctx}" > /dev/null
rm -rf "${_ctx}"
}
# the VM's directory is shared ("z") with the running VM's container
in_image()
{
podman run --rm -v "${VMDIR}:/vm:z" "${IMAGE}" "$@"
}
create()
{
[ $# -eq 3 ] || die "create needs the ssh public key (type, key, comment)"
[ "${1}" = ssh-ed25519 ] && echo "${2}" | grep -Eqx '[A-Za-z0-9+/]{40,}={0,2}' &&
echo "${3}" | grep -Eqx '[A-Za-z0-9._@-]+' || die "bad ssh public key"
[ ! -e "${VMDIR}/disk.qcow2" ] || die "${VMDIR}/disk.qcow2 exists (vm.sh destroy ${OSREL} first)"
for t in podman curl sha256sum xz; do
command -v ${t} > /dev/null || die "${t} is missing"
done
mkdir -p "${VMDIR}"
# no copy-on-write under a disk image (btrfs; elsewhere this does nothing)
chattr +C "${VMDIR}" 2> /dev/null || true
build_image
IMG=FreeBSD-${OSREL}-RELEASE-arm64-aarch64-BASIC-CLOUDINIT-zfs.qcow2.xz
REL=${OSREL}-RELEASE/aarch64/Latest
# The checksums come from FreeBSD itself; the image from the first source that
# has it, including a mirror that keeps old releases (archive.freebsd.org, the
# only official home of an old release, at times stops answering). Transfers
# that stall for a minute are resumed, many times.
OFFICIAL="https://download.freebsd.org/releases/VM-IMAGES https://archive.freebsd.org/old-releases/VM-IMAGES"
SOURCES="${OFFICIAL} https://mirror.math.princeton.edu/pub/FreeBSD/releases/VM-IMAGES"
_probe="curl -fsS -o /dev/null -I --proto =https --connect-timeout 30 --max-time 60"
_curl="curl -fsS --proto =https --connect-timeout 30 --speed-limit 1024 --speed-time 60 --retry 30 --retry-delay 20 --retry-all-errors -C -"
_sum()
{
sed -n "s/^SHA256 (${IMG}) = \([0-9a-f]\{64\}\)\$/\1/p" "${VMDIR}/CHECKSUM.SHA256" 2> /dev/null || true
}
WANT=$(_sum)
for b in ${OFFICIAL}; do
[ -z "${WANT}" ] || break
${_probe} "${b}/${REL}/CHECKSUM.SHA256" 2> /dev/null || continue
rm -f "${VMDIR}/CHECKSUM.SHA256.new"
${_curl} -o "${VMDIR}/CHECKSUM.SHA256.new" "${b}/${REL}/CHECKSUM.SHA256" || continue
mv "${VMDIR}/CHECKSUM.SHA256.new" "${VMDIR}/CHECKSUM.SHA256"
WANT=$(_sum)
done
[ -n "${WANT}" ] || die "no checksum for ${IMG} from download.freebsd.org or archive.freebsd.org"
HAVE=
for b in ${SOURCES}; do
${_probe} "${b}/${REL}/${IMG}" 2> /dev/null || continue
echo ">>> downloading ${b}/${REL}/${IMG}"
${_curl} -o "${VMDIR}/${IMG}" "${b}/${REL}/${IMG}" || continue
HAVE=$(sha256sum "${VMDIR}/${IMG}" | cut -d' ' -f1)
[ "${HAVE}" = "${WANT}" ] && break
echo ">>> checksum mismatch for the image from ${b}" >&2
rm -f "${VMDIR}/${IMG}"
done
[ "${HAVE}" = "${WANT}" ] || die "could not download ${IMG} with the published checksum"
xz -d "${VMDIR}/${IMG}"
mv "${VMDIR}/${IMG%.xz}" "${VMDIR}/disk.qcow2"
in_image qemu-img resize -q /vm/disk.qcow2 "${DISKSIZE}"
in_image cp /usr/share/AAVMF/AAVMF_VARS.fd /vm/efivars.fd
# nuageinit runs a user-data file that is not "#cloud-config" as a root
# script on first boot: install the key for root and nothing else.
mkdir -p "${VMDIR}/seed"
printf 'instance-id: gwbuild-%s\nlocal-hostname: gwbuild-%s\n' "${OSREL}" "$(echo "${OSREL}" | tr . -)" \
> "${VMDIR}/seed/meta-data"
cat > "${VMDIR}/seed/user-data" <<EOF
#!/bin/sh
mkdir -p /root/.ssh
chmod 700 /root/.ssh
echo '${1} ${2} ${3}' > /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
sysrc sshd_enable=YES ifconfig_DEFAULT=SYNCDHCP growfs_enable=YES
printf 'PermitRootLogin prohibit-password\nPasswordAuthentication no\nKbdInteractiveAuthentication no\n' >> /etc/ssh/sshd_config
EOF
chmod 755 "${VMDIR}/seed/user-data"
in_image genisoimage -quiet -output /vm/seed.iso -volid cidata -rational-rock -joliet \
/vm/seed/user-data /vm/seed/meta-data
echo ">>> created ${VMDIR}"
}
start()
{
running && die "already running"
[ -f "${VMDIR}/disk.qcow2" ] || die "no ${VMDIR}/disk.qcow2 (vm.sh create ${OSREL})"
build_image
[ -f "${VMDIR}/swap.qcow2" ] || in_image qemu-img create -q -f qcow2 /vm/swap.qcow2 "${SWAPSIZE}"
podman rm -f "${NAME}" > /dev/null 2>&1 || true
# neoverse-n1: ARMv8.2 with LSE atomics, without the costly emulation of SVE
# and pointer authentication. The ssh port is on the host's loopback only. The
# NIC has no option ROM (iPXE network boot; not in the image, not needed).
# The swap disk (serial gwswap, which build.sh setup looks for) keeps swap off
# ZFS, where it can deadlock when memory runs out, and bypasses the host's
# page cache: the VM swaps when memory is short on the host too.
podman run -d --name "${NAME}" --network host -v "${VMDIR}:/vm:z" "${IMAGE}" \
qemu-system-aarch64 -name "${NAME}" -machine virt,gic-version=3 -cpu neoverse-n1 \
-accel tcg,thread=multi -smp "${CPUS}" -m "${MEM}" \
-drive if=pflash,format=raw,readonly=on,file=/usr/share/AAVMF/AAVMF_CODE.fd \
-drive if=pflash,format=raw,file=/vm/efivars.fd \
-drive file=/vm/disk.qcow2,if=virtio,format=qcow2,discard=unmap \
-drive file=/vm/seed.iso,if=virtio,format=raw,readonly=on \
-drive file=/vm/swap.qcow2,if=none,id=swap,format=qcow2,cache=none,discard=unmap \
-device virtio-blk-pci,drive=swap,serial=gwswap \
-netdev "user,id=n0,hostfwd=tcp:127.0.0.1:${PORT}-:22" -device virtio-net-pci,netdev=n0,romfile= \
-display none -serial file:/vm/console.log > /dev/null
# qemu's own errors (bad options, missing firmware) end it at once
sleep 5
running || { podman logs "${NAME}" >&2; die "qemu exited"; }
echo ">>> started ${NAME}: ${CPUS} CPUs, ${MEM}, ssh on 127.0.0.1:${PORT}, console ${VMDIR}/console.log"
}
stop()
{
if running; then
timeout 300 podman wait "${NAME}" > /dev/null 2>&1 || podman stop -t 30 "${NAME}" > /dev/null
fi
podman rm -f "${NAME}" > /dev/null 2>&1 || true
echo ">>> stopped ${NAME}"
}
case "${CMD}" in
create) create "$@" ;;
start) start ;;
stop) stop ;;
status) running && echo "running (ssh 127.0.0.1:${PORT} on this host)" || echo "stopped" ;;
destroy) stop; rm -rf "${VMDIR}"; echo ">>> removed ${VMDIR}" ;;
*) die "unknown command '${CMD}'" ;;
esac