vmbuild: CDE built on a NetBSD host this tree produces, and in the set.

wm/cde cannot be cross-built from Linux (mk/tools/replace.mk:142 refuses
awk:run when OPSYS != NATIVE_OPSYS), so it is built on a live image from src/
under qemu: tools/vm-boot.cfg puts the console on com0, tools/vmctl.py drives
it, and tools/vmbuild/ holds the stages that bootstrap pkgsrc there with
--prefer-native=yes and build the recipe unchanged.

Two settings, both configuration, both scoped to wm/cde in the build host's
mk.conf: FORCE_C_STD=gnu11 (autoconf 2.72 picks C23, where CDE's 'int f();'
means 'int f(void)') and the C wrapper's append list for the five GCC 14
implicit-declaration errors, the only lever that reaches the ksh93 subtree.

stage6 walks the runtime closure over the @pkgdep lines in +CONTENTS, not over
+DEPENDS (that file is in the binary package, not in the registration
database), and the closure is unpacked into the sysroot rather than pkg_add'ed
so CDE's /etc/dt paths do not land on the build host.  10837 set entries,
checkflist green.
This commit is contained in:
lotherk committed 2026-11-03 13:52:27 +00:00
1 parent c923819a02
commit 980c4113a3
12 files changed
+539

No files matched your search

+42
View File
@@ -126,6 +126,14 @@ ignores it the same way it ignores `var/db/syspkg`.
Removing a package means removing its entries from the list; entries that
existed keep the NetBSD convention and are marked `obsolete`.
What the set holds today: `flex` and `vim`, cross-built by pkgsrc against this
tree's toolchain, and `cde-2.5.3` with its runtime closure, built on the NetBSD
build host (below) and unpacked into the sysroot -- 10837 list entries, and
`checkflist` reports no missing and no extra files. The closure is walked over
`@pkgdep` lines in the package's `+CONTENTS`, not over `+DEPENDS`: that file
exists only inside a binary package, the registration database keeps the
dependencies in `+CONTENTS`.
## Where a Linux build host stops
pkgsrc's cross mode assumes the build host runs the target operating system
@@ -150,6 +158,40 @@ this tree does not do:
Neither the checkflist gate nor the tree depends on these; a package that hits
one is a finding for the report, not a reason to patch pkgsrc.
## The build host for what a Linux host refuses
`wm/cde` trips the first of those, so it is not cross-built: it is built on a
NetBSD amd64 host that this tree produces itself. `build.sh ... live-image`
with `tools/vm-boot.cfg` gives an image whose console is `com0`,
`tools/vmctl.py` drives it, and `tools/vmbuild/` holds the stages that copy
pkgsrc in, bootstrap it with `--prefer-native=yes` and build CDE. Nothing in
pkgsrc and nothing in the recipe changes: the same `wm/cde` builds there.
Two settings were needed, both configuration, both scoped to `wm/cde` in the
build host's `mk.conf` (`tools/vmbuild/mk-cde.conf`):
- The dialect. The recipe runs `autoreconf`; autoconf 2.72's `AC_PROG_CC` takes
the newest standard the compiler supports, C23 on GCC 14, where `int f();`
means `int f(void)`. CDE declares functions that way
(`lib/tt/mini_isam/isaddindex.c:61`) and calls one with three arguments at
line 81, which is an error under C23. `FORCE_C_STD=gnu11` -- the dialect
NetBSD builds its own tree with (`src/share/mk/bsd.sys.mk:68`) -- is pkgsrc's
documented override; the C wrapper appends it after the `-std=` that configure
recorded, which is what makes it win.
- The diagnostics. `programs/dtksh/ksh93` is built by its own build system,
which compiles with `cc` from `PATH` and ignores `CFLAGS`. GCC 14 made
implicit declarations an error in every language mode, and libast decides by a
*successful* compile what `getfsstat()` takes
(`src/lib/libast/features/fs:140`); the probe therefore answered no and
`port/mnt.c` compiled against `struct statfs`, which NetBSD no longer defines
(libc exports `getfsstat`, the headers do not declare it). `CWRAPPERS_APPEND.cc`
-- the hook `mk/compiler/clang.mk` fills in for clang 16+ -- puts the five
GCC 14 downgrades into the wrapper's append list, the only thing that reaches
those compiles.
A Linux host never shows either problem: the first is hidden by `awk:run`, the
second needs a NetBSD base to build the ksh93 subtree at all.
## Definition of done
A change is done when its test is green and it is committed. A build is done
+19
View File
@@ -0,0 +1,19 @@
# boot.cfg for the NetBSD build host VM (not part of the distribution).
#
# The live image built by live-image/ has no VGA console in the VM, so the
# loader and the kernel have to be told to use com0: the loader reads this file
# from the root of the root filesystem, and libsa passes the same devname, addr
# and speed to the kernel as BTINFO_CONSOLE (sys/arch/i386/stand/lib/exec.c,
# read by sys/arch/x86/x86/consinit.c).
#
# Passed to the image build as
# -V IMGFILE_EXTRA="... this-file boot.cfg"
# so the shipped boot.cfg stays untouched.
menu=Boot normally:rndseed /var/db/entropy-file;boot
menu=Boot single user:rndseed /var/db/entropy-file;boot -s
menu=Drop to boot prompt:prompt
default=1
timeout=5
clear=1
consdev=com0,115200
+120
View File
@@ -0,0 +1,120 @@
# tools/vmbuild -- the NetBSD build host
`wm/cde` cannot be cross-built from a Linux host: pkgsrc's cross mode assumes
the build host runs the target operating system, and CDE carries
`USE_TOOLS+=awk:run`, which `mk/tools/replace.mk:142` refuses when
`OPSYS != NATIVE_OPSYS` (see "Where a Linux build host stops" in AGENTS.md).
So CDE is built on a NetBSD amd64 host that this tree produces itself: a live
image from `src/`, running under qemu with KVM, driven over its serial console.
Nothing in pkgsrc and nothing in the recipe changes; the recipes are pkgsrc's.
Everything below was run against the tree as it stands; the logs are in
`build/logs/` (`liveimage-vm-build.log`, `vm-console.log`, and the stage logs).
## 1. The host image
cd src
./build.sh -U -u -m amd64 -M ../build/obj -O ../build/obj -x -X ../xsrc \
-V IMGFILE_EXTRA=../tools/vm-boot.cfg live-image
Result: `build/obj/distrib/amd64/liveimage/emuimage/NetBSD-11.99.9-amd64-live.img`.
`-V IMGFILE_EXTRA=tools/vm-boot.cfg` exists because the live image has no VGA
console in qemu: `vm-boot.cfg` sends the loader and the kernel to `com0`, so
the console is the only way in and the only way to read the build.
## 2. Booting it
The raw image is kept pristine; the VM runs on an overlay:
qemu-img create -f qcow2 -b ../build/obj/.../NetBSD-11.99.9-amd64-live.img \
-F raw build/vm/live.qcow2
qemu-system-x86_64 -machine accel=kvm -cpu host -m 8192 -smp 4 \
-drive file=build/vm/live.qcow2,if=virtio,format=qcow2 \
-netdev user,id=net0,hostfwd=tcp:127.0.0.1:8022-:22 \
-device virtio-net-pci,netdev=net0 \
-serial unix:$PWD/build/vm/console.sock,server=on,wait=off \
-monitor unix:$PWD/build/vm/monitor.sock,server=on,wait=off \
-display none -vga none
`tools/vmctl.py` drives the serial console and appends the transcript to
`build/logs/vm-console.log`. Once `~/.ssh/authorized_keys` exists in the VM the
22 forward is the easier way in:
ssh -p 8022 -i build/vm/id_vm root@127.0.0.1
## 3. Handing files to the VM
The VM has no route out; qemu's user networking maps `10.0.2.2` to the host's
loopback, so the host serves what the VM fetches:
python3 -m http.server 8001 --bind 127.0.0.1 --directory tools/vmbuild
python3 -m http.server 8000 --bind 127.0.0.1 --directory <the distfiles dir>
python3 -m http.server 8002 --bind 127.0.0.1 \
--directory build/obj/releasedir/amd64/binary/sets
Port 8001 serves these scripts, `vm-mk.conf`, `mk-cde.conf` and the public key
installed as `/root/.ssh/authorized_keys`; 8000 serves pkgsrc's distfiles
(`DISTDIR` is the shared one, flat, which is the layout pkgsrc expects of a
master site); 8002 serves `xbase`, `xcomp`, `xetc` and `xfont` out of this
tree's own release directory, so the host's X is the X the target ships.
## 4. The stages, in order
Run each with `sh /tmp/stageN.sh` after fetching it from port 8001.
stage1-fetch.sh pkgsrc tree and vm-mk.conf into /usr
stage2-xsets.sh xbase, xcomp, xetc, xfont into /
stage3-bootstrap.sh pkgsrc bootstrapped into /usr/pkg, --prefer-native=yes
stage4-mkconf.sh the wm/cde block appended to /usr/pkg/etc/mk.conf
stage5-cde.sh bmake FORCE_C_STD=gnu11 install in wm/cde
stage6-pack.sh the runtime closure of cde packed into /var/tmp/usrpkg.tar.gz
Each is run over the console or with `sh -s < tools/vmbuild/stageN.sh` on the
ssh side; stage6 in particular is small enough to pipe in and needs no fetch.
`--prefer-native=yes` is not optional: without it bootstrap writes
`PREFER_PKGSRC=yes` on a non-NetBSD host, and every library base already ships
would be built a second time. On this host "native" is the running base, so
pkgsrc uses the tree's curses, zlib, expat, fontconfig and X libraries.
## 5. Getting the result into the sysroot
scp -P 8022 -i build/vm/id_vm root@127.0.0.1:/var/tmp/usrpkg.tar.gz build/
tar -xzpf build/usrpkg.tar.gz -C build/obj/destdir.amd64
tools/makronix-set.sh
The tar is the package's runtime closure only -- what `pkg_add` would pull in
when it installs CDE, walked over the dependency records -- not the build tools
that were needed to produce it. It is unpacked rather than `pkg_add`ed into the
sysroot because CDE's install script writes `/etc/dt` (CONF_FILES,
RCD_SCRIPTS), and
`pkg_add -p <prefix>` only relocates the prefix: the `/etc` paths would land on
the build host. `tools/makronix-set.sh` then writes the file list and the
METALOG records from what is in the tree.
## 6. What this produced, measured
The closure of `cde-2.5.3` is 16 packages (cde, motif, tcl, ksh93, opensp, lmdb,
libXft, libjpeg-turbo, png, freetype2, fontconfig, brotli, sqlite3,
pam-pwauth_suid, and the two Adobe bitmap font packs), 8410 files, 69 MB as a
tar.gz. Unpacked into `build/obj/destdir.amd64` (no name collided with what the
cross build had already put under `/usr/pkg`), it took `tools/makronix-set.sh`
to 10837 list entries and 10825 METALOG records, and `checkflist` then ran green
with `-L base,x`.
Two things worth knowing when reading that:
- The dependencies are the `@pkgdep` lines in `/usr/pkg/pkgdb/<pkg>/+CONTENTS`.
`+DEPENDS` is a member of the *binary package*, not of the registration
database, so a closure walked over it finds nothing.
- `--prefer-native=yes` did what it says where the base ships the library:
`libz.so.1` and `libsqlite3.so.1` are not in `/usr/pkg/lib` in the VM and the
CDE binaries link against `/usr/lib` for them. freetype, fontconfig, png and
brotli are not in this base at all -- only under `/usr/pkg/lib` -- so those
packages are the single copy, not a duplicate.
Every one of the 57 distinct `NEEDED` libraries across the 159 ELF objects under
`/usr/pkg` resolves inside the sysroot, and CDE's own libraries are on the
binaries' RPATH (`/usr/pkg/lib:/usr/X11R7/lib:/usr/pkg/dt/lib`).
+33
View File
@@ -0,0 +1,33 @@
.ifdef BSD_PKG_MK # the blocks below are pkgsrc's, not some other mk.conf reader
# wm/cde: two parts of CDE 2.5.3 are older than the compiler NetBSD ships.
#
# 1. The dialect. The recipe runs autoreconf, autoconf 2.72's AC_PROG_CC takes
# the newest standard the compiler supports -- C23 on GCC 14 -- and under
# C23 `int f();` means `int f(void)`. CDE declares functions that way
# (lib/tt/mini_isam/isaddindex.c), so the call with three arguments is an
# error. NetBSD builds its own tree with gnu11 (src/share/mk/bsd.sys.mk);
# FORCE_C_STD pins the same dialect, and the C wrapper appends it after the
# -std= configure recorded, which is what makes it win. It is passed on the
# bmake command line by tools/vmbuild/stage5-cde.sh.
#
# 2. The diagnostics. programs/dtksh/ksh93 is built by its own build system,
# which compiles with `cc` from PATH and ignores CFLAGS. GCC 14 made
# implicit declarations an error in every language mode; libast's feature
# probes decide by a *successful* compile what getfsstat() takes, so the
# probe answered "no" and port/mnt.c compiled against `struct statfs`, which
# NetBSD does not define any more (libc still exports getfsstat(3), the
# headers no longer declare it). The wrapper's append list is the one lever
# that reaches those compiles -- pkgsrc itself uses it for clang 16+ in
# mk/compiler/clang.mk (_WERROR_CLANG16), and that comment says it was
# written with GCC 14 in mind.
.if ${PKGPATH} == "wm/cde"
CWRAPPERS_APPEND.cc+= -Wno-error=implicit-function-declaration
CWRAPPERS_APPEND.cc+= -Wno-error=implicit-int
CWRAPPERS_APPEND.cc+= -Wno-error=int-conversion
CWRAPPERS_APPEND.cc+= -Wno-error=incompatible-pointer-types
CWRAPPERS_APPEND.cc+= -Wno-error=return-mismatch
.endif
.endif
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# stage 1: get pkgsrc and the mk.conf into the NetBSD build host VM.
# Served by the host's http server on 10.0.2.2 (qemu user networking maps that
# to the host's loopback).
set -e
cd /usr
ftp -Vo /var/tmp/pkgsrc.tar.gz http://10.0.2.2:8001/pkgsrc.tar.gz
tar -xzpf /var/tmp/pkgsrc.tar.gz -C /usr
ftp -Vo /var/tmp/vm-mk.conf http://10.0.2.2:8001/vm-mk.conf
ls /usr/pkgsrc/wm/cde/Makefile
echo STAGE1-OK
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# stage 2: the X sets. A live image carries base and comp but not xbase/xcomp,
# and CDE is an X application: with X11_TYPE=native pkgsrc needs the X headers,
# libraries and fonts where the distribution puts them, /usr/X11R7. The sets
# come from this tree's own release directory, so the VM's X is byte for byte
# the X the target ships.
set -e
cd /var/tmp
for s in xbase xcomp xetc xfont; do
ftp -Vo /var/tmp/$s.tar.xz http://10.0.2.2:8002/$s.tar.xz
tar -xzpf /var/tmp/$s.tar.xz -C /
rm -f /var/tmp/$s.tar.xz
done
ls -l /usr/X11R7/lib/libX11.so /usr/X11R7/include/X11/Xlib.h
echo STAGE2-OK
+24
View File
@@ -0,0 +1,24 @@
#!/bin/sh
# stage 3b: bootstrap pkgsrc into /usr/pkg.
#
# The first attempt bootstrapped bmake and pkg_* into /opt/pkg-bootstrap while
# LOCALBASE was /usr/pkg, and that split does not work: mk/bsd.prefs.mk sets
# TOOLBASE := ${LOCALBASE}, so the build looked for mktools under
# /usr/pkg/libexec/mktools while the bootstrap tools had gone into
# /opt/pkg-bootstrap (p5-gettext: "mk-buildlink-symlinks: not found").
# pkgsrc's model is one prefix; the bootstrap tools are separated from the
# distribution copy at the end instead, by package.
set -e
rm -rf /opt/pkg-bootstrap /tmp/bootwork
# /usr/pkg already holds the packages the failed attempt installed into it;
# they are in /var/tmp/packages as binary packages, so pkgsrc reinstalls them
# instead of rebuilding.
rm -rf /usr/pkg /var/tmp/work
cd /usr/pkgsrc/bootstrap
./bootstrap --prefer-native=yes \
--prefix /usr/pkg \
--workdir /tmp/bootwork \
--mk-fragment /var/tmp/vm-mk.conf
mkdir -p /var/tmp/distfiles /var/tmp/work /var/tmp/packages
/usr/pkg/bin/bmake -V MAKE_VERSION
echo STAGE3B-OK
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
# stage 4: the rest of mk.conf, and the build directories.
#
# bootstrap(1) writes /usr/pkg/etc/mk.conf from the bootstrap preamble plus the
# --mk-fragment file, inside its own ".ifdef BSD_PKG_MK". The wm/cde block is
# appended afterwards by this stage rather than being part of the fragment, so
# that it is visible as a separate decision: the fragment describes the build
# host, and this block describes one package's encounter with GCC 14. It
# carries its own guard, because mk.conf is read again by the build itself.
#
# Running it twice is harmless: the block is skipped when it is already there.
set -e
export PATH=/usr/pkg/bin:/usr/pkg/sbin:$PATH
MkConf=/usr/pkg/etc/mk.conf
if grep -q 'CWRAPPERS_APPEND.cc' "${MkConf}"; then
echo "stage4: the wm/cde block is already in ${MkConf}"
else
ftp -Vo /var/tmp/mk-cde.conf http://10.0.2.2:8001/mk-cde.conf
cat /var/tmp/mk-cde.conf >> "${MkConf}"
fi
mkdir -p /var/tmp/distfiles /var/tmp/work /var/tmp/packages
cd /usr/pkgsrc/wm/cde
bmake -V LOCALBASE -V DISTDIR -V WRKOBJDIR -V MASTER_SITE_OVERRIDE
echo STAGE4-OK
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# stage 5: build and install wm/cde on the NetBSD build host.
#
# The recipe is pkgsrc's, unchanged: no USE_TOOLS hack, no patch to the package
# and none to pkgsrc. What makes it build here is that this host is NetBSD --
# the cross-compilation refusal in mk/tools/replace.mk:142 does not fire -- plus
# two settings, both configuration:
#
# /usr/pkg/etc/mk.conf the C wrapper's append list for wm/cde, written by
# stage4 from mk-cde.conf. It is the only lever that
# reaches the ksh93 subtree, which compiles with `cc`
# from PATH and ignores CFLAGS.
# FORCE_C_STD=gnu11 the dialect NetBSD builds its own tree with
# (src/share/mk/bsd.sys.mk). Given on the command
# line rather than in mk.conf so the setting sits next
# to the build it applies to; both work. Without it,
# autoconf 2.72's AC_PROG_CC picks C23 on GCC 14, where
# CDE's "int f();" means "int f(void)".
#
# The first run of this stage is what showed the two problems; 5c through 5e in
# build/vmshare are the iterations that isolated them. This is the one that
# installed cde-2.5.3 into /usr/pkg.
set -e
export PATH=/usr/pkg/bin:/usr/pkg/sbin:$PATH
cd /usr/pkgsrc/wm/cde
bmake clean
bmake FORCE_C_STD=gnu11 install
echo STAGE5-OK
+65
View File
@@ -0,0 +1,65 @@
#!/bin/sh
# stage 6: pack the runtime closure of CDE out of /usr/pkg.
#
# What the distribution gets is not everything the build touched: autoconf,
# automake, perl, gmake, help2man and the rest are build tools. What a
# Makronix system needs is what pkg_add would pull in when it installs the CDE
# package, so the closure is walked over the package's dependency records --
# pkg_install keeps them as "@pkgdep" lines inside +CONTENTS once the package is
# registered -- and every package in it contributes its files (pkg_info -L).
#
# -q is not cosmetic: without it pkg_info -L prints an "Information for <pkg>:"
# header and a "Files:" line, which tar then tries to open as paths.
set -e
PATH=/usr/pkg/bin:/usr/pkg/sbin:$PATH
export PATH
cd /usr/pkg/pkgdb
set -- cde-2.5.3
seen=" "
while [ $# -gt 0 ]; do
pkg="$1"
shift
case "$seen" in
*" ${pkg} "*) continue ;;
esac
seen="${seen}${pkg} "
if [ -f "${pkg}/+CONTENTS" ]; then
for dep in $(awk '$1 == "@pkgdep" { print $2 }' "${pkg}/+CONTENTS"); do
# -e alone: -q suppresses the *name*, which is the
# whole answer here.
resolved=$(pkg_info -e "${dep}" | head -1)
if [ -n "${resolved}" ]; then
set -- "$@" "${resolved}"
fi
done
fi
done
echo "--- runtime closure:"
for p in ${seen}; do echo "${p}"; done | sort
: > /var/tmp/files.txt
for p in ${seen}; do
pkg_info -qL "${p}"
done | sort -u > /var/tmp/files.txt
echo "--- files: $(wc -l < /var/tmp/files.txt)"
# Every path in the list must exist: a +FILES/+CONTENTS entry for a file the
# install rewrote or removed would otherwise make tar fail halfway through.
: > /var/tmp/missing.txt
while IFS= read -r f; do
[ -e "${f}" ] || echo "${f}" >> /var/tmp/missing.txt
done < /var/tmp/files.txt
if [ -s /var/tmp/missing.txt ]; then
echo "--- listed but absent, dropped from the archive:"
cat /var/tmp/missing.txt
awk 'NR == FNR { drop[$0] = 1; next } !($0 in drop)' \
/var/tmp/missing.txt /var/tmp/files.txt > /var/tmp/files.txt.new
mv /var/tmp/files.txt.new /var/tmp/files.txt
echo "--- files now: $(wc -l < /var/tmp/files.txt)"
fi
tar -czpf /var/tmp/usrpkg.tar.gz -T /var/tmp/files.txt
ls -l /var/tmp/usrpkg.tar.gz
echo STAGE6-OK
+27
View File
@@ -0,0 +1,27 @@
# mk.conf for the pkgsrc build host inside the VM (not part of the tree's
# cross configuration: this one is a native build, host == target == NetBSD
# amd64 11.99.9, which is exactly what pkgsrc's cross mode assumes and what a
# Linux host cannot provide).
LOCALBASE= /usr/pkg
PKG_SYSCONFBASE= /etc
VARBASE= /var
DISTDIR= /var/tmp/distfiles
WRKOBJDIR= /var/tmp/work
PACKAGES= /var/tmp/packages
# Base is NetBSD 11.99.9 built from this tree: its libraries (curses, zlib,
# expat, fontconfig, the X libraries, libintl) are the ones the distribution
# ships, so packages use them instead of a second copy under /usr/pkg.
PREFER_PKGSRC=
PREFER_NATIVE= yes
# No internet in the build host: every archive comes from the shared DISTDIR on
# the host, served on loopback through qemu's user networking (10.0.2.2 is the
# host). pkgsrc joins this with the DISTNAME, and the shared distfiles
# directory is flat, which is the layout pkgsrc expects of a master site.
MASTER_SITE_OVERRIDE= http://10.0.2.2:8000/
# The VM has four vCPUs.
MAKE_JOBS= 4
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
# vmctl.py -- drive a NetBSD virtual machine's serial console.
#
# Why this exists: the CDE build needs a NetBSD build host (pkgsrc's
# mk/tools/replace.mk refuses "USE_TOOLS+=awk:run" whenever OPSYS !=
# NATIVE_OPSYS, which is what a cross-OS build from Linux is). The host is a
# NetBSD amd64 image built by this tree's own build.sh, run under qemu with
# KVM, and the only way in is the serial console.
#
# Usage:
# vmctl.py --sock PATH --log PATH [--do ACTION ...]
#
# Actions, in order:
# wait:SECONDS:REGEX read the console until REGEX matches (SECONDS=0: no limit)
# send:TEXT send TEXT; \n sends Enter, \\n a literal backslash-n
# sleep:SECONDS wait
# mark:TEXT write TEXT to the log as a step marker
#
# The console transcript is appended to --log, so the evidence stays in the
# tree the way AGENTS.md asks for it.
import argparse
import os
import re
import select
import socket
import sys
import time
CHUNK = 4096
class Console:
def __init__(self, sock_path, log_path, quiet=False):
self.log = open(log_path, "ab", buffering=0)
self.quiet = quiet
deadline = time.time() + 60
while True:
try:
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(sock_path)
break
except OSError:
self.sock.close()
if time.time() > deadline:
raise SystemExit("vmctl: cannot connect to %s" % sock_path)
time.sleep(0.5)
self.buf = b""
def _pump(self, deadline):
wait = None
if deadline:
wait = max(0.0, deadline - time.time())
r, _, _ = select.select([self.sock], [], [], wait if wait is not None else 1.0)
if not r:
if deadline and time.time() >= deadline:
return False
return True
try:
data = self.sock.recv(CHUNK)
except OSError:
raise SystemExit("vmctl: console closed")
if not data:
raise SystemExit("vmctl: console EOF")
self.log.write(data)
self.buf += data
if not self.quiet:
sys.stdout.write(data.decode("utf-8", "replace"))
sys.stdout.flush()
return True
def wait_for(self, pattern, timeout):
rx = re.compile(pattern.encode())
deadline = time.time() + timeout if timeout else None
while True:
m = rx.search(self.buf)
if m:
self.buf = self.buf[m.end():]
return True
if not self._pump(deadline):
return False
def send(self, text):
self.sock.sendall(text.encode())
time.sleep(0.05)
def close(self):
try:
self.sock.close()
finally:
self.log.close()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--sock", required=True)
ap.add_argument("--log", required=True)
ap.add_argument("--do", action="append", default=[])
ap.add_argument("--quiet", action="store_true")
args = ap.parse_args()
con = Console(args.sock, args.log, args.quiet)
for action in args.do:
kind, _, rest = action.partition(":")
if kind == "wait":
timeout, _, pattern = rest.partition(":")
if not pattern:
raise SystemExit("vmctl: wait needs SECONDS:REGEX")
ok = con.wait_for(pattern, float(timeout))
if not ok:
raise SystemExit("vmctl: timeout waiting for %r" % pattern)
elif kind == "send":
con.send(rest.replace("\\n", "\n"))
elif kind == "sleep":
time.sleep(float(rest))
elif kind == "mark":
con.log.write(("\n=== vmctl: %s ===\n" % rest).encode())
if not args.quiet:
print("=== vmctl: %s ===" % rest)
else:
raise SystemExit("vmctl: unknown action %r" % kind)
con.close()
if __name__ == "__main__":
main()