- K2: config/lock-<version> gives tools, src, ports, plugins and core their exact commits; build stops when a checkout differs (a tag moved upstream, or src moved on), and fetches tags without --force. build.sh lock resolves and writes them. lock-26.7.9 is what 26.7.9 was built from, checked against the upstream tags. - K3: verify --root reports symlinks that lead outside the tree or nowhere, which publish (rsync -L) would follow; such a path is now reported instead of crashing verify. - K6: RELEASE.md no longer says core trusts only our key (it also trusts upstream's, for changelog and bogons), and names no host or user. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1467 lines
65 KiB
Python
1467 lines
65 KiB
Python
# Copyright 2026 Karst Tech
|
|
# SPDX-License-Identifier: BSD-2-Clause
|
|
"""Tests for the shell scripts that run on the firewall and in the build.
|
|
|
|
Run: python3 -m unittest discover -s release/tests
|
|
|
|
The scripts are run for real, against a fixture root (GW_ROOT) where they
|
|
take one, with fake commands first in PATH, so the same tests run on Linux
|
|
and on the FreeBSD build VM.
|
|
"""
|
|
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
REPO = os.path.dirname(os.path.dirname(HERE))
|
|
KERNEL_HOOK = os.path.join(REPO, "rc.d", "20-kernel-update")
|
|
FETCH_REPAIR = os.path.join(REPO, "release", "fetch-distfile.sh")
|
|
# Fake commands: each logs its argv to $FAKE_LOG; tests add their own.
|
|
FAKES = {
|
|
"logger": "exit 0",
|
|
"df": 'echo "Filesystem 1024-blocks Used Avail Capacity Mounted"; echo "fake 81920 0 ${FAKE_FREE_KB:-80000} 0% /"',
|
|
}
|
|
|
|
|
|
class Fixture:
|
|
def __init__(self, tmp):
|
|
self.tmp = tmp
|
|
self.root = os.path.join(tmp, "root")
|
|
self.bin = os.path.join(tmp, "bin")
|
|
self.log = os.path.join(tmp, "calls.log")
|
|
os.makedirs(self.bin)
|
|
for name, body in FAKES.items():
|
|
self.make_fake(name, body)
|
|
|
|
def make_fake(self, name, body):
|
|
path = os.path.join(self.bin, name)
|
|
with open(path, "w") as f:
|
|
f.write(f'#!/bin/sh\necho "{name} $*" >> "$FAKE_LOG"\n{body}\n')
|
|
os.chmod(path, 0o755)
|
|
|
|
def path(self, rel):
|
|
return os.path.join(self.root, rel.lstrip("/"))
|
|
|
|
def write(self, rel, data, mode=0o644):
|
|
p = self.path(rel)
|
|
os.makedirs(os.path.dirname(p), exist_ok=True)
|
|
with open(p, "wb" if isinstance(data, bytes) else "w") as f:
|
|
f.write(data)
|
|
os.chmod(p, mode)
|
|
return p
|
|
|
|
def run(self, script, *args, **env):
|
|
e = {"PATH": f"{self.bin}:/usr/bin:/bin", "GW_ROOT": self.root, "FAKE_LOG": self.log,
|
|
"TMPDIR": self.tmp}
|
|
e.update(env)
|
|
return subprocess.run(["sh", script, *args], env=e, capture_output=True, text=True)
|
|
|
|
def calls(self):
|
|
if not os.path.exists(self.log):
|
|
return []
|
|
with open(self.log) as f:
|
|
return f.read().splitlines()
|
|
|
|
|
|
class KernelHookTest(unittest.TestCase):
|
|
OLD, NEW, OLD_DTB, NEW_DTB = b"old-kernel" * 100, b"new-kernel" * 120, b"old-dtb", b"new-dtb"
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.mkdtemp(prefix="gw-kernel-")
|
|
self.addCleanup(shutil.rmtree, self.tmp)
|
|
self.fx = Fixture(self.tmp)
|
|
self.fx.write("/boot/msdos/kernel.img", self.OLD)
|
|
self.fx.write("/boot/msdos/dtb/mono-gateway-dk.dtb", self.OLD_DTB)
|
|
self.fx.write("/boot/kernel/kernel.bin", self.NEW)
|
|
self.fx.write("/boot/dtb/freescale/mono-gateway-dk.dtb", self.NEW_DTB)
|
|
|
|
def run_hook(self, **env):
|
|
return self.fx.run(KERNEL_HOOK, **env)
|
|
|
|
def content(self, rel):
|
|
p = self.fx.path(rel)
|
|
if not os.path.exists(p):
|
|
return None
|
|
with open(p, "rb") as f:
|
|
return f.read()
|
|
|
|
def assertUntouched(self):
|
|
self.assertEqual(self.content("/boot/msdos/kernel.img"), self.OLD)
|
|
self.assertEqual(self.content("/boot/msdos/dtb/mono-gateway-dk.dtb"), self.OLD_DTB)
|
|
self.assertEqual(self.content("/boot/kernel/kernel.bin"), self.NEW, "the kernel set's file")
|
|
self.assertIsNone(self.content("/boot/msdos/kernel.new"))
|
|
|
|
def test_update(self):
|
|
r = self.run_hook()
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(self.content("/boot/msdos/kernel.img"), self.NEW)
|
|
self.assertEqual(self.content("/boot/msdos/kernel.old"), self.OLD)
|
|
self.assertEqual(self.content("/boot/msdos/dtb/mono-gateway-dk.dtb"), self.NEW_DTB)
|
|
self.assertEqual(self.content("/boot/msdos/dtb/mono-gateway-dk.old"), self.OLD_DTB)
|
|
# left as the kernel set installed them: the health audit checks them
|
|
self.assertEqual(self.content("/boot/kernel/kernel.bin"), self.NEW)
|
|
self.assertEqual(self.content("/boot/dtb/freescale/mono-gateway-dk.dtb"), self.NEW_DTB)
|
|
self.assertIsNone(self.content("/boot/msdos/kernel.new"))
|
|
logged = len(self.fx.calls())
|
|
r = self.run_hook()
|
|
self.assertEqual(r.returncode, 0, "second shutdown is a no-op")
|
|
self.assertEqual(self.content("/boot/msdos/kernel.old"), self.OLD)
|
|
self.assertEqual(self.content("/boot/msdos/dtb/mono-gateway-dk.old"), self.OLD_DTB)
|
|
self.assertEqual(len(self.fx.calls()), logged, "nothing logged when nothing changes")
|
|
|
|
def test_nothing_to_do(self):
|
|
os.unlink(self.fx.path("/boot/kernel/kernel.bin"))
|
|
r = self.run_hook()
|
|
self.assertEqual(r.returncode, 0)
|
|
self.assertEqual(self.content("/boot/msdos/kernel.img"), self.OLD)
|
|
self.assertEqual(self.fx.calls(), [])
|
|
|
|
def test_reinstall_same_kernel_keeps_backup(self):
|
|
self.fx.write("/boot/msdos/kernel.old", b"older")
|
|
self.fx.write("/boot/kernel/kernel.bin", self.OLD)
|
|
self.fx.write("/boot/dtb/freescale/mono-gateway-dk.dtb", self.OLD_DTB)
|
|
r = self.run_hook()
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(self.content("/boot/msdos/kernel.img"), self.OLD)
|
|
self.assertEqual(self.content("/boot/msdos/kernel.old"), b"older")
|
|
self.assertEqual(self.content("/boot/kernel/kernel.bin"), self.OLD)
|
|
self.assertEqual(self.fx.calls(), [])
|
|
|
|
def test_installed_kernel_on_a_full_partition(self):
|
|
# nothing to install: no space check, no message on every shutdown
|
|
self.fx.write("/boot/kernel/kernel.bin", self.OLD)
|
|
self.fx.write("/boot/dtb/freescale/mono-gateway-dk.dtb", self.OLD_DTB)
|
|
r = self.run_hook(FAKE_FREE_KB="1")
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(r.stderr, "")
|
|
self.assertEqual(self.fx.calls(), [])
|
|
|
|
def test_same_kernel_new_device_tree(self):
|
|
self.fx.write("/boot/kernel/kernel.bin", self.OLD)
|
|
r = self.run_hook()
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(self.content("/boot/msdos/kernel.img"), self.OLD)
|
|
self.assertIsNone(self.content("/boot/msdos/kernel.old"), "the kernel was not replaced")
|
|
self.assertEqual(self.content("/boot/msdos/dtb/mono-gateway-dk.dtb"), self.NEW_DTB)
|
|
|
|
def test_installed_kernel_without_device_tree_in_set(self):
|
|
self.fx.write("/boot/kernel/kernel.bin", self.OLD)
|
|
os.unlink(self.fx.path("/boot/dtb/freescale/mono-gateway-dk.dtb"))
|
|
r = self.run_hook(FAKE_FREE_KB="1")
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(self.fx.calls(), [])
|
|
|
|
def test_fat_not_mounted(self):
|
|
os.unlink(self.fx.path("/boot/msdos/kernel.img"))
|
|
r = self.run_hook()
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertIn("not mounted", r.stderr)
|
|
self.assertEqual(self.content("/boot/kernel/kernel.bin"), self.NEW)
|
|
|
|
def test_not_enough_space(self):
|
|
r = self.run_hook(FAKE_FREE_KB="1")
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertIn("bytes free", r.stderr)
|
|
self.assertUntouched()
|
|
|
|
def test_stale_backup_counts_as_free_space(self):
|
|
self.fx.write("/boot/msdos/kernel.old", b"x" * (3 * 1024 * 1024))
|
|
r = self.run_hook(FAKE_FREE_KB="1")
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(self.content("/boot/msdos/kernel.img"), self.NEW)
|
|
|
|
def test_copy_failure_keeps_old_kernel(self):
|
|
self.fx.make_fake("cp", 'case "$2" in *kernel.new) echo partial > "$2"; exit 1;; esac; exec /bin/cp "$@"')
|
|
r = self.run_hook()
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertIn("failed", r.stderr)
|
|
self.assertUntouched()
|
|
|
|
def test_install_failure_restores_old_kernel(self):
|
|
self.fx.make_fake("mv", 'case "$1" in *kernel.new) exit 1;; esac; exec /bin/mv "$@"')
|
|
r = self.run_hook()
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertIn("restored the previous one", r.stderr)
|
|
self.assertUntouched()
|
|
|
|
def test_dtb_failure_restores_old_kernel(self):
|
|
self.fx.make_fake("cp", 'case "$2" in *dtb*.new) exit 1;; esac; exec /bin/cp "$@"')
|
|
r = self.run_hook()
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertIn("device tree update failed", r.stderr)
|
|
self.assertEqual(self.content("/boot/msdos/kernel.img"), self.OLD)
|
|
self.assertEqual(self.content("/boot/msdos/dtb/mono-gateway-dk.dtb"), self.OLD_DTB)
|
|
self.assertEqual(self.content("/boot/kernel/kernel.bin"), self.NEW)
|
|
|
|
def test_kernel_set_without_dtb(self):
|
|
os.unlink(self.fx.path("/boot/dtb/freescale/mono-gateway-dk.dtb"))
|
|
r = self.run_hook()
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(self.content("/boot/msdos/kernel.img"), self.NEW)
|
|
self.assertEqual(self.content("/boot/msdos/dtb/mono-gateway-dk.dtb"), self.OLD_DTB)
|
|
|
|
|
|
# A GitHub-generated patch as distinfo recorded it (9-digit abbreviations) and as
|
|
# GitHub serves it today (10 digits).
|
|
PATCH_9 = """From a54ea1a2f7d858fe6eb2976d688c251e64acf8f8 Mon Sep 17 00:00:00 2001
|
|
Subject: [PATCH] libpkg: disable package scripts reaper
|
|
|
|
---
|
|
libpkg/lua_scripts.c | 2 +-
|
|
libpkg/scripts.c | 2 +-
|
|
diff --git a/libpkg/lua_scripts.c b/libpkg/lua_scripts.c
|
|
index 0327cae46..0f9a634f2 100644
|
|
--- a/libpkg/lua_scripts.c
|
|
+++ b/libpkg/lua_scripts.c
|
|
@@ -1 +1 @@
|
|
-\t\treturn (EPKG_FATAL);
|
|
+\t\t/* return (EPKG_FATAL); */
|
|
diff --git a/libpkg/scripts.c b/libpkg/scripts.c
|
|
index bf0c388a9..e4960ff69
|
|
--- a/libpkg/scripts.c
|
|
+++ b/libpkg/scripts.c
|
|
@@ -1 +1 @@
|
|
-x
|
|
+y
|
|
"""
|
|
PATCH_10 = (PATCH_9.replace("0327cae46..0f9a634f2", "0327cae463..0f9a634f2e")
|
|
.replace("bf0c388a9..e4960ff69", "bf0c388a9f..e4960ff69a"))
|
|
GH_URL = "https://github.com/opnsense/pkg/commit/a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch"
|
|
|
|
|
|
class FetchDistfileTest(unittest.TestCase):
|
|
"""release/fetch-distfile.sh, the FETCH_CMD build.sh repairs distfiles with."""
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.mkdtemp(prefix="gw-fetch-")
|
|
self.addCleanup(shutil.rmtree, self.tmp)
|
|
self.fx = Fixture(self.tmp)
|
|
self.distdir = os.path.join(self.tmp, "distfiles")
|
|
os.makedirs(self.distdir)
|
|
self.served = os.path.join(self.tmp, "served.patch")
|
|
with open(self.served, "w") as f:
|
|
f.write(PATCH_10)
|
|
# the wrapper's own "fetch -q -o FILE URL" gets GitHub's current patch; the
|
|
# framework's attempt ("fetch -Fpr ...") fails on the size unless FAKE_DIRECT
|
|
self.fx.make_fake("fetch", """if [ "$1 $2" = "-q -o" ]; then
|
|
[ -z "${FAKE_DOWNLOAD_FAIL:-}" ] || exit 1
|
|
n=$(grep -c '^fetch -q -o' "$FAKE_LOG")
|
|
[ "$n" -gt "${FAKE_DOWNLOAD_FAILS:-0}" ] || exit 1
|
|
exec cp "$FAKE_SERVED" "$3"
|
|
fi
|
|
[ -n "${FAKE_DIRECT:-}" ] || exit 1
|
|
for a; do last=$a; done
|
|
echo direct > "${last##*/}"
|
|
""")
|
|
self.fx.make_fake("sleep", "exit 0")
|
|
|
|
def fetch(self, *args, **env):
|
|
e = {"PATH": f"{self.fx.bin}:/usr/bin:/bin", "FAKE_LOG": self.fx.log, "FAKE_SERVED": self.served}
|
|
e.update(env)
|
|
return subprocess.run(["sh", FETCH_REPAIR, *args], env=e, cwd=self.distdir,
|
|
capture_output=True, text=True)
|
|
|
|
def files(self):
|
|
out = []
|
|
for d, _, names in os.walk(self.distdir):
|
|
out += [os.path.relpath(os.path.join(d, n), self.distdir) for n in names]
|
|
return sorted(out)
|
|
|
|
def test_recovers_recorded_patch(self):
|
|
r = self.fetch("-S", str(len(PATCH_9)), GH_URL)
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertIn("9 digits", r.stdout)
|
|
name = "a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch"
|
|
self.assertEqual(self.files(), [name], "no temporary files left")
|
|
with open(os.path.join(self.distdir, name)) as f:
|
|
self.assertEqual(f.read(), PATCH_9)
|
|
|
|
def test_direct_fetch_passes_through(self):
|
|
r = self.fetch("-S", "123", GH_URL, FAKE_DIRECT="1")
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(len(self.fx.calls()), 1, "no second download")
|
|
self.assertEqual(self.fx.calls()[0], f"fetch -Fpr -S 123 {GH_URL}")
|
|
|
|
def test_output_in_subdirectory(self):
|
|
os.makedirs(os.path.join(self.distdir, "sub"))
|
|
r = self.fetch("-S", str(len(PATCH_9)), "-o", "sub/x.patch", GH_URL)
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(self.files(), ["sub/x.patch"])
|
|
|
|
def test_pull_and_compare_patches(self):
|
|
for url in ("https://github.com/o/r/pull/12.patch", "https://github.com/o/r/compare/a...b.diff"):
|
|
r = self.fetch("-S", str(len(PATCH_9)), url)
|
|
self.assertEqual(r.returncode, 0, url + r.stderr)
|
|
self.assertEqual(self.files(), ["12.patch", "a...b.diff"])
|
|
|
|
def test_other_urls_are_not_rewritten(self):
|
|
for url in ("https://example.org/a54ea1a.patch",
|
|
"https://evil.example/github.com/o/r/commit/x.patch",
|
|
"https://github.com.evil.example/o/r/commit/x.patch",
|
|
"http://github.com/o/r/commit/x.patch",
|
|
"https://github.com/o/r/archive/x.tar.gz"):
|
|
r = self.fetch("-S", str(len(PATCH_9)), url)
|
|
self.assertEqual(r.returncode, 1, url)
|
|
self.assertEqual(len(self.fx.calls()), 5, "only the framework's own attempts")
|
|
self.assertEqual(self.files(), [])
|
|
|
|
def test_no_matching_size(self):
|
|
r = self.fetch("-S", str(len(PATCH_9) + 1), GH_URL)
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertIn("no abbreviation", r.stderr)
|
|
self.assertEqual(self.files(), [], "nothing written, no temporary files left")
|
|
|
|
def test_needs_numeric_size(self):
|
|
for args in ((GH_URL,), ("-S", "12x", GH_URL), ("-S", "", GH_URL)):
|
|
self.assertEqual(self.fetch(*args).returncode, 1, args)
|
|
self.assertEqual(self.files(), [])
|
|
|
|
def test_download_failure(self):
|
|
r = self.fetch("-S", str(len(PATCH_9)), GH_URL, FAKE_DOWNLOAD_FAIL="1")
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertEqual(self.files(), [])
|
|
downloads = [c for c in self.fx.calls() if c.startswith("fetch -q -o")]
|
|
self.assertEqual(len(downloads), 3, "three attempts")
|
|
self.assertEqual([c for c in self.fx.calls() if c.startswith("sleep")], ["sleep 60"] * 2)
|
|
|
|
def test_download_retried(self):
|
|
# GitHub turned the first two requests away
|
|
r = self.fetch("-S", str(len(PATCH_9)), GH_URL, FAKE_DOWNLOAD_FAILS="2")
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(self.files(), ["a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch"])
|
|
self.assertEqual(len([c for c in self.fx.calls() if c.startswith("sleep")]), 2)
|
|
|
|
def test_direct_fetch_is_not_retried(self):
|
|
# the framework's own attempt fails and moves on to its next site
|
|
r = self.fetch("-S", "123", "https://example.org/x.tar.gz")
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertEqual(len(self.fx.calls()), 1)
|
|
|
|
CB_URL = "https://codeberg.org/BSDforge/sysinfo/archive/1.0.4.tar.gz?dummy=/sysinfo-1.0.4.tar.gz"
|
|
|
|
def codeberg(self, *args, archive=b"x" * 100, **env):
|
|
"""fetch-distfile.sh with a fake git whose archive is ARCHIVE."""
|
|
with open(os.path.join(self.tmp, "archive"), "wb") as f:
|
|
f.write(archive)
|
|
self.fx.make_fake("git", f"""case "$1" in
|
|
clone) [ -z "${{FAKE_CLONE_FAIL:-}}" ] || exit 128; for a; do last=$a; done; mkdir "$last" ;;
|
|
-C) cat "{self.tmp}/archive" ;;
|
|
esac
|
|
""")
|
|
return self.fetch(*args, **env)
|
|
|
|
def test_codeberg_archive_made_from_tag(self):
|
|
r = self.codeberg("-S", "100", self.CB_URL)
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertIn("made from the tag 1.0.4 of codeberg.org/BSDforge/sysinfo", r.stdout)
|
|
self.assertEqual(self.files(), ["sysinfo-1.0.4.tar.gz"], "no temporary files left")
|
|
with open(os.path.join(self.distdir, "sysinfo-1.0.4.tar.gz"), "rb") as f:
|
|
self.assertEqual(f.read(), b"x" * 100)
|
|
git = [c for c in self.fx.calls() if c.startswith("git ")]
|
|
self.assertEqual(len(git), 2)
|
|
self.assertRegex(git[0], r"^git clone -q --bare --depth 1 --branch 1\.0\.4 "
|
|
r"https://codeberg\.org/BSDforge/sysinfo\.git \./\.fetch-distfile\.\w+\.git$")
|
|
self.assertRegex(git[1], r"^git -C \./\.fetch-distfile\.\w+\.git archive --format=tar\.gz -6 "
|
|
r"--prefix=sysinfo/ refs/tags/1\.0\.4$")
|
|
|
|
def test_codeberg_archive_plain_url_and_output(self):
|
|
url = "https://codeberg.org/o/my.repo/archive/v2.1+x.tar.gz"
|
|
r = self.codeberg("-S", "100", "-o", "out.tgz", url)
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(self.files(), ["out.tgz"])
|
|
self.assertIn("--prefix=my.repo/ refs/tags/v2.1+x", self.fx.calls()[-1])
|
|
|
|
def test_codeberg_archive_wrong_size(self):
|
|
r = self.codeberg("-S", "99", self.CB_URL)
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertIn("does not have the size 99", r.stderr)
|
|
self.assertEqual(self.files(), [], "nothing written, no temporary files left")
|
|
|
|
def test_codeberg_clone_failure(self):
|
|
r = self.codeberg("-S", "100", self.CB_URL, FAKE_CLONE_FAIL="1")
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertEqual(self.files(), [])
|
|
|
|
def test_codeberg_rejects_crafted_urls(self):
|
|
for url in ("https://codeberg.org/-o/r/archive/1.0.tar.gz",
|
|
"https://codeberg.org/o/-r/archive/1.0.tar.gz",
|
|
"https://codeberg.org/o/r/archive/-1.0.tar.gz",
|
|
"https://codeberg.org/o/r/archive/--upload-pack=x.tar.gz",
|
|
"https://codeberg.org/o/r/archive/../../x.tar.gz",
|
|
"https://codeberg.org/o/r/x/archive/1.0.tar.gz",
|
|
"https://codeberg.org/o/r/archive/1;rm -rf x.tar.gz",
|
|
"https://codeberg.org/o/r/archive/$(id).tar.gz",
|
|
"https://codeberg.org/o/r/archive/1.0.zip",
|
|
"https://codeberg.org.evil.example/o/r/archive/1.0.tar.gz",
|
|
"https://evil.example/codeberg.org/o/r/archive/1.0.tar.gz",
|
|
"http://codeberg.org/o/r/archive/1.0.tar.gz"):
|
|
r = self.codeberg("-S", "100", url)
|
|
self.assertEqual(r.returncode, 1, url)
|
|
self.assertEqual([c for c in self.fx.calls() if c.startswith("git ")], [], "git never run")
|
|
self.assertEqual(self.files(), [])
|
|
|
|
def test_rejects_unsafe_output_names(self):
|
|
for out in ("../evil.patch", "/tmp/evil.patch", "a/../../evil.patch", "..", ".", "dir/"):
|
|
r = self.fetch("-S", str(len(PATCH_9)), "-o", out, GH_URL)
|
|
self.assertEqual(r.returncode, 1, out)
|
|
self.assertEqual(self.files(), [])
|
|
self.assertFalse(os.path.exists(os.path.join(self.tmp, "evil.patch")))
|
|
|
|
|
|
BUILD = os.path.join(REPO, "release", "build.sh")
|
|
|
|
# what the ports framework prints in tools' ports chroot when a distfile cannot be
|
|
# fetched while a port is built with its dependencies (from the 26.1.11 build)
|
|
FETCH_FAIL_PKG = """===> License BSD2CLAUSE accepted by the user
|
|
=> a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch doesn't seem to exist in /usr/ports/distfiles.
|
|
=> Attempting to fetch https://github.com/opnsense/pkg/commit/a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch
|
|
fetch: https://github.com/opnsense/pkg/commit/a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch: size mismatch: expected 2827, actual 2831
|
|
=> Attempting to fetch http://distcache.FreeBSD.org/ports-distfiles/a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch
|
|
fetch: http://distcache.FreeBSD.org/ports-distfiles/a54ea1a2f7d858fe6eb2976d688c251e64acf8f8.patch: Not Found
|
|
=> Couldn't fetch it - please try to retrieve this
|
|
=> port manually into /usr/ports/distfiles and try again.
|
|
*** Error code 1
|
|
|
|
Stop.
|
|
make[1]: stopped in /usr/ports/ports-mgmt/pkg
|
|
*** Error code 1
|
|
|
|
Stop.
|
|
make: stopped in /usr/ports/devel/binutils
|
|
"""
|
|
CHECKSUM_FAIL = """=> SHA256 Checksum mismatch for foo-1.0.tar.gz.
|
|
===> Refetch for 1 more times files: foo-1.0.tar.gz
|
|
=> SHA256 Checksum mismatch for foo-1.0.tar.gz.
|
|
=> Giving up on fetching files: foo-1.0.tar.gz
|
|
Make sure the Makefile and distinfo file (/usr/ports/net/foo/distinfo)
|
|
are up to date.
|
|
*** Error code 1
|
|
|
|
Stop.
|
|
make[2]: stopped in /usr/ports/net/foo
|
|
*** Error code 1
|
|
|
|
Stop.
|
|
make[1]: stopped in /usr/ports/net/foo-wrapper
|
|
"""
|
|
BUILD_FAIL = """foo.c:12:1: error: expected ';' after top level declarator
|
|
*** Error code 1
|
|
|
|
Stop.
|
|
make[1]: stopped in /usr/ports/devel/foo/work/foo-1.0
|
|
*** Error code 1
|
|
|
|
Stop.
|
|
make: stopped in /usr/ports/devel/foo
|
|
"""
|
|
|
|
|
|
class FetchFailuresTest(unittest.TestCase):
|
|
"""build.sh's fetch_failures: which ports' distfiles to repair after a ports step."""
|
|
|
|
def failures(self, log):
|
|
with tempfile.NamedTemporaryFile("w", suffix=".log", delete=False) as f:
|
|
f.write(log)
|
|
self.addCleanup(os.unlink, f.name)
|
|
func = subprocess.run(["sed", "-n", "/^fetch_failures()/,/^}/p", BUILD],
|
|
capture_output=True, text=True, check=True).stdout
|
|
self.assertIn("fetch_failures()", func)
|
|
r = subprocess.run(["sh", "-c", func + '\nfetch_failures "$1"', "sh", f.name],
|
|
capture_output=True, text=True)
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
return r.stdout.split()
|
|
|
|
def test_names_the_port_that_failed_not_the_one_depending_on_it(self):
|
|
self.assertEqual(self.failures(FETCH_FAIL_PKG), ["ports-mgmt/pkg"])
|
|
|
|
def test_checksum_mismatch(self):
|
|
self.assertEqual(self.failures(CHECKSUM_FAIL), ["net/foo"])
|
|
|
|
def test_build_failure_is_not_a_fetch_failure(self):
|
|
self.assertEqual(self.failures(BUILD_FAIL), [])
|
|
self.assertEqual(self.failures(""), [])
|
|
|
|
def test_several_failures_once_each_sorted(self):
|
|
log = FETCH_FAIL_PKG + BUILD_FAIL + CHECKSUM_FAIL + FETCH_FAIL_PKG
|
|
self.assertEqual(self.failures(log), ["net/foo", "ports-mgmt/pkg"])
|
|
|
|
def test_skips_work_directories_to_the_port(self):
|
|
log = ("=> Couldn't fetch it - please try to retrieve this\n"
|
|
"make[2]: stopped in /usr/ports/devel/foo/work/foo-1.0\n"
|
|
"make[1]: stopped in /usr/ports/devel/foo\n")
|
|
self.assertEqual(self.failures(log), ["devel/foo"])
|
|
|
|
def test_only_port_names(self):
|
|
# build output is not trusted: names become arguments of make -C /usr/ports/...
|
|
for bad in ("../..", "devel/..", "../etc", "devel/*", "devel/foo bar", "devel/$(id)",
|
|
"devel/.hidden", "Devel/foo", "devel/foo;id", "/etc/passwd"):
|
|
log = ("=> Couldn't fetch it - please try to retrieve this\n"
|
|
f"make[1]: stopped in /usr/ports/{bad}\n")
|
|
self.assertEqual(self.failures(log), [], bad)
|
|
|
|
def test_flavoured_and_plus_names(self):
|
|
log = ("=> Couldn't fetch it - please try to retrieve this\n"
|
|
"make[1]: stopped in /usr/ports/devel/py-setuptools\n"
|
|
"=> Couldn't fetch it - please try to retrieve this\n"
|
|
"make[1]: stopped in /usr/ports/devel/libstdc++_stldoc_4.2.2\n")
|
|
self.assertEqual(self.failures(log), ["devel/libstdc++_stldoc_4.2.2", "devel/py-setuptools"])
|
|
|
|
|
|
class DistfilesInSetTest(unittest.TestCase):
|
|
"""build.sh's distfiles_in_set: whether a port's distfiles need no download."""
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.mkdtemp(prefix="gw-dist-")
|
|
self.addCleanup(shutil.rmtree, self.tmp)
|
|
self.fx = Fixture(self.tmp)
|
|
# the ports tree's answers for "make -C /usr/ports/PORT ARCH=aarch64 -V VAR"
|
|
self.fx.make_fake("make", """case "$1 $2 $3 $4 $5" in
|
|
"-C /usr/ports/cat/port ARCH=aarch64 -V DIST_SUBDIR") echo "${FAKE_SUB:-}";;
|
|
"-C /usr/ports/cat/port ARCH=aarch64 -V ALLFILES") echo "${FAKE_FILES:-}";;
|
|
*) exit 2;;
|
|
esac""")
|
|
self.func = build_function("port_distfiles") + build_function("distfiles_in_set")
|
|
|
|
def sh(self, call, files, sub, *args):
|
|
return subprocess.run(["sh", "-c", self.func + "\n" + call, "sh", *args],
|
|
env={"PATH": f"{self.fx.bin}:/usr/bin:/bin", "FAKE_LOG": self.fx.log,
|
|
"FAKE_FILES": files, "FAKE_SUB": sub},
|
|
cwd=self.tmp, capture_output=True, text=True)
|
|
|
|
def in_set(self, listing, files, sub="", port="cat/port"):
|
|
r = self.sh('distfiles_in_set "$1" "$2"', files, sub, port, listing)
|
|
self.assertIn(r.returncode, (0, 1), r.stderr)
|
|
return r.returncode == 0
|
|
|
|
def entries(self, files, sub="", port="cat/port"):
|
|
r = self.sh('port_distfiles "$1"', files, sub, port)
|
|
return r.returncode, r.stdout
|
|
|
|
def test_entries(self):
|
|
self.assertEqual(self.entries(" a-1.0.tar.gz\tx.patch y.diff "),
|
|
(0, "distfiles/a-1.0.tar.gz\ndistfiles/x.patch\ndistfiles/y.diff\n"))
|
|
self.assertEqual(self.entries("perl-5.42.2.tar.xz", sub="perl"), (0, "distfiles/perl/perl-5.42.2.tar.xz\n"))
|
|
self.assertEqual(self.entries(""), (0, ""))
|
|
self.assertEqual(self.entries("a", port="cat/unknown")[0], 1)
|
|
|
|
LISTING = "distfiles/\ndistfiles/a-1.0.tar.gz\ndistfiles/x.patch\ndistfiles/perl/perl-5.42.2.tar.xz\n"
|
|
|
|
def test_all_present(self):
|
|
self.assertTrue(self.in_set(self.LISTING, "a-1.0.tar.gz x.patch"))
|
|
|
|
def test_one_missing(self):
|
|
self.assertFalse(self.in_set(self.LISTING, "a-1.0.tar.gz x.patch y.patch"))
|
|
|
|
def test_dist_subdir(self):
|
|
self.assertTrue(self.in_set(self.LISTING, "perl-5.42.2.tar.xz ", sub="perl"))
|
|
self.assertFalse(self.in_set(self.LISTING, "perl-5.42.2.tar.xz"), "not without the subdirectory")
|
|
self.assertFalse(self.in_set(self.LISTING, "a-1.0.tar.gz", sub="perl"))
|
|
|
|
def test_port_without_distfiles(self):
|
|
self.assertTrue(self.in_set(self.LISTING, ""))
|
|
self.assertTrue(self.in_set("", ""))
|
|
|
|
def test_empty_set(self):
|
|
self.assertFalse(self.in_set("", "a-1.0.tar.gz"))
|
|
|
|
def test_whole_names_only(self):
|
|
listing = "distfiles/a-1.0.tar.gz.part\ndistfiles/xa-1.0.tar.gz\ndistfiles/aX1.0.tar.gz\na-1.0.tar.gz\n"
|
|
for name in ("a-1.0.tar.gz", "a.1.0.tar.gz", "a-1.0"):
|
|
self.assertFalse(self.in_set(listing, name), name)
|
|
|
|
def test_glob_characters_are_not_expanded(self):
|
|
open(os.path.join(self.tmp, "a-1.0.tar.gz"), "w").close()
|
|
self.assertFalse(self.in_set(self.LISTING, "*.tar.gz"))
|
|
self.assertTrue(self.in_set("distfiles/*.tar.gz\n", "*.tar.gz"))
|
|
|
|
def test_make_failure_means_missing(self):
|
|
self.assertFalse(self.in_set(self.LISTING, "", port="cat/unknown"))
|
|
|
|
|
|
def build_function(name, subst=()):
|
|
"""The text of one function of build.sh (to run it alone), paths substituted."""
|
|
func = subprocess.run(["sed", "-n", f"/^{name}()/,/^}}/p", BUILD],
|
|
capture_output=True, text=True, check=True).stdout
|
|
assert func.startswith(f"{name}()"), name
|
|
for a, b in subst:
|
|
func = func.replace(a, b)
|
|
return func
|
|
|
|
|
|
class SalvagePortsTest(unittest.TestCase):
|
|
"""build.sh's salvage_ports: an interrupted ports step's packages into the set."""
|
|
|
|
ID = "26.1 26.1.11 0123abcd"
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.mkdtemp(prefix="gw-salvage-")
|
|
self.addCleanup(shutil.rmtree, self.tmp)
|
|
self.stage = os.path.join(self.tmp, "stage", ".pkg", "All")
|
|
os.makedirs(self.stage)
|
|
self.set = os.path.join(self.tmp, "packages-26.1.11-aarch64.tar")
|
|
self.run_file = os.path.join(self.tmp, "ports.run")
|
|
self.func = build_function("salvage_ports")
|
|
# the set as tools makes it, holding one package the stage also has
|
|
setdir = os.path.join(self.tmp, "setdir")
|
|
os.makedirs(os.path.join(setdir, "All"))
|
|
open(os.path.join(setdir, ".abi_hint"), "w").close()
|
|
self.make_pkg(os.path.join(setdir, "All"), "old-1.0.pkg")
|
|
self.make_pkg(self.stage, "old-1.0.pkg")
|
|
subprocess.run(["tar", "-C", setdir, "-cf", self.set, "./.abi_hint", "./All/old-1.0.pkg"], check=True)
|
|
|
|
def make_pkg(self, d, name, manifest=True):
|
|
# a package as pkg writes it: its manifests first, then the files
|
|
src = os.path.join(self.tmp, "pkgsrc")
|
|
shutil.rmtree(src, ignore_errors=True)
|
|
os.makedirs(os.path.join(src, "usr", "local", "lib"))
|
|
members = ["usr/local/lib/libfoo.so"]
|
|
with open(os.path.join(src, members[0]), "wb") as f:
|
|
f.write(os.urandom(5000))
|
|
if manifest:
|
|
for m in ("+COMPACT_MANIFEST", "+MANIFEST"):
|
|
with open(os.path.join(src, m), "w") as f:
|
|
f.write('{"name":"foo"}')
|
|
members = ["+COMPACT_MANIFEST", "+MANIFEST"] + members
|
|
path = os.path.join(d, name)
|
|
subprocess.run(["tar", "-czf", path, "-C", src, *members], check=True)
|
|
return path
|
|
|
|
def salvage(self, id_=ID, stage=None, set_=None):
|
|
r = subprocess.run(["sh", "-c", 'step() { echo ">>> $*"; }\n' + self.func + '\nsalvage_ports "$@"',
|
|
"sh", stage or self.stage, set_ or self.set, id_],
|
|
env={"PATH": "/usr/bin:/bin", "PORTS_RUN": self.run_file},
|
|
capture_output=True, text=True)
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
return r.stdout
|
|
|
|
def entries(self, set_=None):
|
|
return subprocess.run(["tar", "-tf", set_ or self.set], capture_output=True, text=True,
|
|
check=True).stdout.split("\n")[:-1]
|
|
|
|
def started(self, id_=ID):
|
|
with open(self.run_file, "w") as f:
|
|
f.write(id_ + "\n")
|
|
|
|
def test_first_step_adds_nothing_records_the_build(self):
|
|
self.make_pkg(self.stage, "new-2.0.pkg")
|
|
self.salvage()
|
|
self.assertEqual(self.entries(), ["./.abi_hint", "./All/old-1.0.pkg"])
|
|
with open(self.run_file) as f:
|
|
self.assertEqual(f.read(), self.ID + "\n")
|
|
|
|
def test_stage_of_another_build_is_ignored(self):
|
|
self.started("26.1 26.1.10 0123abcd")
|
|
self.make_pkg(self.stage, "new-2.0.pkg")
|
|
self.salvage()
|
|
self.assertEqual(self.entries(), ["./.abi_hint", "./All/old-1.0.pkg"])
|
|
with open(self.run_file) as f:
|
|
self.assertEqual(f.read(), self.ID + "\n")
|
|
|
|
def test_adds_the_finished_packages(self):
|
|
self.started()
|
|
a = self.make_pkg(self.stage, "new-2.0.pkg")
|
|
self.make_pkg(self.stage, "py313-foo-1.2_1.pkg")
|
|
out = self.salvage()
|
|
self.assertIn("salvaged 2 packages", out)
|
|
self.assertEqual(sorted(self.entries()), ["./.abi_hint", "./All/new-2.0.pkg", "./All/old-1.0.pkg",
|
|
"./All/py313-foo-1.2_1.pkg"])
|
|
x = os.path.join(self.tmp, "x")
|
|
os.makedirs(x)
|
|
subprocess.run(["tar", "-C", x, "-xf", self.set], check=True)
|
|
with open(a, "rb") as f1, open(os.path.join(x, "All", "new-2.0.pkg"), "rb") as f2:
|
|
self.assertEqual(f1.read(), f2.read())
|
|
|
|
def test_twice_adds_nothing_more(self):
|
|
self.started()
|
|
self.make_pkg(self.stage, "new-2.0.pkg")
|
|
self.salvage()
|
|
before = self.entries()
|
|
self.assertNotIn("salvaged", self.salvage())
|
|
self.assertEqual(self.entries(), before)
|
|
|
|
def test_incomplete_package_is_skipped(self):
|
|
self.started()
|
|
p = self.make_pkg(self.stage, "cut-1.0.pkg")
|
|
with open(p, "rb") as f:
|
|
data = f.read()
|
|
with open(p, "wb") as f:
|
|
f.write(data[:len(data) // 2])
|
|
# an empty file is an empty archive to FreeBSD's tar
|
|
open(os.path.join(self.stage, "empty-1.0.pkg"), "w").close()
|
|
self.make_pkg(self.stage, "nomanifest-1.0.pkg", manifest=False)
|
|
self.make_pkg(self.stage, "whole-1.0.pkg")
|
|
out = self.salvage()
|
|
self.assertIn("incomplete: ./All/cut-1.0.pkg", out)
|
|
self.assertIn("incomplete: ./All/empty-1.0.pkg", out)
|
|
self.assertIn("incomplete: ./All/nomanifest-1.0.pkg", out)
|
|
self.assertIn("salvaged 1 packages", out)
|
|
self.assertNotIn("./All/cut-1.0.pkg", self.entries())
|
|
self.assertIn("./All/whole-1.0.pkg", self.entries())
|
|
|
|
def test_without_a_set_makes_one(self):
|
|
self.started()
|
|
os.unlink(self.set)
|
|
self.make_pkg(self.stage, "new-2.0.pkg")
|
|
self.salvage()
|
|
self.assertEqual(sorted(self.entries()), ["./All/new-2.0.pkg", "./All/old-1.0.pkg"])
|
|
|
|
def test_without_a_stage_or_packages(self):
|
|
self.started()
|
|
self.salvage(stage=os.path.join(self.tmp, "nonexistent"))
|
|
shutil.rmtree(self.stage)
|
|
os.makedirs(self.stage)
|
|
self.salvage()
|
|
self.assertEqual(self.entries(), ["./.abi_hint", "./All/old-1.0.pkg"])
|
|
|
|
def test_awkward_names(self):
|
|
# names are not options to tar, and match whole set entries only
|
|
self.started()
|
|
for name in ("-rf.pkg", "a b-1.0.pkg", "old-1.0.pkg.pkg", "ld-1.0.pkg"):
|
|
self.make_pkg(self.stage, name)
|
|
self.salvage()
|
|
self.assertEqual(sorted(self.entries()),
|
|
sorted(["./.abi_hint", "./All/old-1.0.pkg", "./All/-rf.pkg", "./All/a b-1.0.pkg",
|
|
"./All/old-1.0.pkg.pkg", "./All/ld-1.0.pkg"]))
|
|
|
|
|
|
class VmMemoryTest(unittest.TestCase):
|
|
"""build.sh's vm_memory: swap on the VM's swap disk, a small ZFS cache."""
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.mkdtemp(prefix="gw-vmmem-")
|
|
self.addCleanup(shutil.rmtree, self.tmp)
|
|
self.fx = Fixture(self.tmp)
|
|
self.fstab = os.path.join(self.tmp, "fstab")
|
|
with open(self.fstab, "w") as f:
|
|
f.write("/dev/gpt/rootfs\t/\tufs\trw\t1\t1\n")
|
|
self.gpt = os.path.join(self.tmp, "gpt")
|
|
os.makedirs(self.gpt)
|
|
self.swaps = os.path.join(self.tmp, "swaps")
|
|
open(self.swaps, "w").close()
|
|
self.loader = os.path.join(self.tmp, "loader.conf")
|
|
with open(self.loader, "w") as f:
|
|
f.write('zfs_load="YES"\n')
|
|
self.sysctl_conf = os.path.join(self.tmp, "sysctl.conf")
|
|
with open(self.sysctl_conf, "w") as f:
|
|
f.write("# sysctl.conf\n")
|
|
self.func = build_function("vm_memory", [("/etc/fstab", self.fstab), ("/dev/gpt/", self.gpt + "/"),
|
|
("/boot/loader.conf", self.loader),
|
|
("/etc/sysctl.conf", self.sysctl_conf)])
|
|
fakes = {
|
|
"sysctl": 'case "$*" in "-n kern.disks") echo "${FAKE_DISKS}";; esac',
|
|
"diskinfo": 'eval "echo \\${FAKE_IDENT_${2#/dev/}:-}"',
|
|
"gpart": f'[ "$1" = add ] && touch "{self.gpt}/gwswap"; exit 0',
|
|
"swapctl": f'echo "Device 1K-blocks Used"; cat "{self.swaps}"',
|
|
"swapon": f'echo "$1 16777216 0" >> "{self.swaps}"',
|
|
}
|
|
for name, body in fakes.items():
|
|
self.fx.make_fake(name, body)
|
|
|
|
def vm_memory(self, disks, **idents):
|
|
env = {"PATH": f"{self.fx.bin}:/usr/bin:/bin", "FAKE_LOG": self.fx.log, "FAKE_DISKS": disks}
|
|
env.update({f"FAKE_IDENT_{k}": v for k, v in idents.items()})
|
|
r = subprocess.run(["sh", "-c", self.func + "\nvm_memory"], env=env, capture_output=True, text=True)
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
calls = self.fx.calls()
|
|
os.unlink(self.fx.log)
|
|
return [c for c in calls if not c.startswith(("diskinfo", "swapctl", "sysctl -n"))]
|
|
|
|
def fstab_lines(self):
|
|
with open(self.fstab) as f:
|
|
return f.read().splitlines()
|
|
|
|
def loader_lines(self):
|
|
with open(self.loader) as f:
|
|
return f.read().splitlines()
|
|
|
|
def sysctl_lines(self):
|
|
with open(self.sysctl_conf) as f:
|
|
return f.read().splitlines()
|
|
|
|
def test_not_in_the_vm(self):
|
|
self.assertEqual(self.vm_memory("vtbd0 vtbd1", vtbd0="BHYVE-1234", vtbd1=""), [])
|
|
self.assertEqual(self.vm_memory(""), [])
|
|
self.assertEqual(len(self.fstab_lines()), 1)
|
|
self.assertEqual(self.loader_lines(), ['zfs_load="YES"'])
|
|
self.assertEqual(self.sysctl_lines(), ["# sysctl.conf"])
|
|
|
|
def test_sets_up_swap_and_cache(self):
|
|
# the swap disk need not be the last one (it came up as vtbd0 in the VM)
|
|
calls = self.vm_memory("vtbd0 vtbd1 vtbd2", vtbd0="", vtbd2="gwswap")
|
|
self.assertEqual(calls, ["gpart create -s gpt vtbd2", "gpart add -t freebsd-swap -l gwswap vtbd2",
|
|
f"swapon {self.gpt}/gwswap", "sysctl vfs.zfs.arc_max=2147483648",
|
|
"sysctl vm.pfault_oom_attempts=-1"])
|
|
self.assertEqual(self.fstab_lines()[1], f"{self.gpt}/gwswap\tnone\tswap\tsw\t0\t0")
|
|
self.assertEqual(self.loader_lines(), ['zfs_load="YES"', 'vfs.zfs.arc_max="2147483648"'])
|
|
self.assertEqual(self.sysctl_lines(), ["# sysctl.conf", "vm.pfault_oom_attempts=-1"])
|
|
|
|
def test_overrides_an_earlier_cache_setting(self):
|
|
with open(self.loader, "a") as f:
|
|
f.write('vfs.zfs.arc_max="8G"\n')
|
|
self.vm_memory("vtbd0", vtbd0="gwswap")
|
|
self.assertEqual(self.loader_lines()[-1], 'vfs.zfs.arc_max="2147483648"')
|
|
|
|
def test_again_changes_nothing_on_the_disk(self):
|
|
self.vm_memory("vtbd0 vtbd2", vtbd2="gwswap")
|
|
calls = self.vm_memory("vtbd0 vtbd2", vtbd2="gwswap")
|
|
self.assertEqual(calls, ["sysctl vfs.zfs.arc_max=2147483648", "sysctl vm.pfault_oom_attempts=-1"])
|
|
self.assertEqual(len(self.fstab_lines()), 2)
|
|
self.assertEqual(len(self.loader_lines()), 2)
|
|
self.assertEqual(len(self.sysctl_lines()), 2)
|
|
|
|
def test_overrides_an_earlier_page_wait_setting(self):
|
|
with open(self.sysctl_conf, "a") as f:
|
|
f.write("vm.pfault_oom_attempts=3\n")
|
|
self.vm_memory("vtbd0", vtbd0="gwswap")
|
|
self.assertEqual(self.sysctl_lines()[-1], "vm.pfault_oom_attempts=-1")
|
|
|
|
def test_after_a_reboot_swap_is_turned_on_again(self):
|
|
self.vm_memory("vtbd2", vtbd2="gwswap")
|
|
open(self.swaps, "w").close()
|
|
self.assertIn(f"swapon {self.gpt}/gwswap", self.vm_memory("vtbd2", vtbd2="gwswap"))
|
|
self.assertEqual(len(self.fstab_lines()), 2)
|
|
|
|
|
|
class PortsMakeConfTest(unittest.TestCase):
|
|
"""build.sh's ports_make_conf: lang/rust's jobs capped at one per 768 MB."""
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.mkdtemp(prefix="gw-mkconf-")
|
|
self.addCleanup(shutil.rmtree, self.tmp)
|
|
self.fx = Fixture(self.tmp)
|
|
self.fx.make_fake("sysctl", '[ "$*" = "-n hw.physmem" ] && echo "${FAKE_PHYSMEM}"')
|
|
self.conf = os.path.join(self.tmp, "make.conf")
|
|
with open(self.conf, "w") as f:
|
|
f.write("BATCH=\t\t\tyes\n")
|
|
self.func = build_function("ports_make_conf")
|
|
self.deps = os.path.join(self.tmp, "deps")
|
|
os.makedirs(os.path.join(self.deps, "config"))
|
|
with open(os.path.join(self.deps, "config", "make-26.1.conf"), "w") as f:
|
|
f.write("# pins\nCADDY_CUSTOM_PLUGINS=\ta@v1 \\\n\t\t\tb@v2\n")
|
|
|
|
def appended(self, physmem, series="26.1"):
|
|
env = {"PATH": f"{self.fx.bin}:/usr/bin:/bin", "FAKE_LOG": self.fx.log, "FAKE_PHYSMEM": str(physmem),
|
|
"DEPS": self.deps, "SERIES": series}
|
|
r = subprocess.run(["sh", "-c", self.func + '\nports_make_conf "$1"', "sh", self.conf],
|
|
env=env, capture_output=True, text=True)
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
with open(self.conf) as f:
|
|
lines = f.read().splitlines()
|
|
self.assertEqual(lines[0], "BATCH=\t\t\tyes")
|
|
return lines[-1]
|
|
|
|
def test_build_vm(self):
|
|
# the 12 GB VM's hw.physmem
|
|
self.assertEqual(self.appended(12851638272), "lang_rust_VARS=\tMAKE_JOBS_NUMBER_LIMIT=15")
|
|
|
|
def test_large_host(self):
|
|
self.assertEqual(self.appended(64 << 30), "lang_rust_VARS=\tMAKE_JOBS_NUMBER_LIMIT=85")
|
|
|
|
def test_series_settings_first(self):
|
|
self.appended(12851638272)
|
|
with open(self.conf) as f:
|
|
self.assertEqual(f.read(), "BATCH=\t\t\tyes\n# pins\nCADDY_CUSTOM_PLUGINS=\ta@v1 \\\n\t\t\tb@v2\n"
|
|
"lang_rust_VARS=\tMAKE_JOBS_NUMBER_LIMIT=15\n")
|
|
|
|
def test_series_without_settings(self):
|
|
self.appended(12851638272, series="26.7")
|
|
with open(self.conf) as f:
|
|
self.assertEqual(f.read(), "BATCH=\t\t\tyes\nlang_rust_VARS=\tMAKE_JOBS_NUMBER_LIMIT=15\n")
|
|
|
|
def test_at_least_one_job(self):
|
|
self.assertEqual(self.appended(805306367), "lang_rust_VARS=\tMAKE_JOBS_NUMBER_LIMIT=1")
|
|
self.assertEqual(self.appended(805306368), "lang_rust_VARS=\tMAKE_JOBS_NUMBER_LIMIT=1")
|
|
|
|
|
|
class PortsCleanTest(unittest.TestCase):
|
|
"""build.sh's ports_clean: tools' ports.sh removes all work directories after a port."""
|
|
|
|
# tools' ports.sh, the build loop's lines with "clean" in them (26.1.11)
|
|
LOOP = (
|
|
'echo "${PORTSLIST}\n'
|
|
'clean.up.post.build" | while read PORT_ORIGIN; do\n'
|
|
'\tif [ \\${PORT} = "clean.up.post.build" ]; then\n'
|
|
'\t\tcontinue\n'
|
|
'\tfi\n'
|
|
'\tif ! make -C ${PORTSDIR}/\\${PORT} install \\\n'
|
|
'\t USE_PACKAGE_DEPENDS=yes \\${MAKE_ARGS}; then\n'
|
|
'\t\tmake -C ${PORTSDIR}/\\${PORT} clean \\${MAKE_ARGS}\n'
|
|
'\t\tcontinue\n'
|
|
'\tfi\n'
|
|
'\tmake -C ${PORTSDIR}/\\${PORT} clean \\${MAKE_ARGS}\n'
|
|
'done\n'
|
|
)
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.mkdtemp(prefix="gw-pclean-")
|
|
self.addCleanup(shutil.rmtree, self.tmp)
|
|
self.ports_sh = os.path.join(self.tmp, "ports.sh")
|
|
self.func = build_function("die") + build_function("ports_clean")
|
|
|
|
def run_clean(self, text):
|
|
with open(self.ports_sh, "w") as f:
|
|
f.write(text)
|
|
r = subprocess.run(["sh", "-c", self.func + '\nports_clean "$1"', "sh", self.ports_sh],
|
|
capture_output=True, text=True)
|
|
with open(self.ports_sh) as f:
|
|
out = f.read()
|
|
self.assertEqual(os.listdir(self.tmp), ["ports.sh"])
|
|
return r, out
|
|
|
|
def test_both_cleans_replaced(self):
|
|
r, out = self.run_clean(self.LOOP)
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
expected = self.LOOP.replace("\t\tmake -C ${PORTSDIR}/\\${PORT} clean \\${MAKE_ARGS}\n",
|
|
"\t\trm -rf /usr/obj${PORTSDIR}\n")
|
|
expected = expected.replace("\tmake -C ${PORTSDIR}/\\${PORT} clean \\${MAKE_ARGS}\n",
|
|
"\trm -rf /usr/obj${PORTSDIR}\n")
|
|
self.assertEqual(out, expected)
|
|
self.assertEqual(out.count("rm -rf /usr/obj${PORTSDIR}"), 2)
|
|
self.assertNotIn(" clean ", out)
|
|
self.assertIn('clean.up.post.build" ]', out)
|
|
|
|
def test_changed_tools_refused(self):
|
|
# one clean only, already replaced, or a clean that does more
|
|
for text in (self.LOOP.replace("\tmake -C ${PORTSDIR}/\\${PORT} clean \\${MAKE_ARGS}\ndone",
|
|
"done"),
|
|
self.LOOP.replace("make -C ${PORTSDIR}/\\${PORT} clean \\${MAKE_ARGS}",
|
|
"rm -rf /usr/obj${PORTSDIR}"),
|
|
self.LOOP.replace("clean \\${MAKE_ARGS}\n", "clean \\${MAKE_ARGS} || true\n"),
|
|
""):
|
|
with self.subTest(text=text[-80:]):
|
|
r, out = self.run_clean(text)
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertIn("not the two port cleans expected", r.stderr)
|
|
self.assertEqual(out, text)
|
|
|
|
|
|
class ScanImageTest(unittest.TestCase):
|
|
"""build.sh's scan_image: every ELF file in the image's datasets is aarch64."""
|
|
|
|
DATASETS = ["gwscan", "gwscan/ROOT", "gwscan/ROOT/default", "gwscan/usr", "gwscan/usr/home"]
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.mkdtemp(prefix="gw-scan-")
|
|
self.addCleanup(shutil.rmtree, self.tmp)
|
|
self.fx = Fixture(self.tmp)
|
|
self.ds = os.path.join(self.tmp, "datasets")
|
|
self.work = os.path.join(self.tmp, "work")
|
|
os.makedirs(self.work)
|
|
self.listing = os.path.join(self.tmp, "zfs-list")
|
|
self.set_datasets(self.DATASETS)
|
|
self.add("gwscan/ROOT/default", "bin/sh", "ELF-arm")
|
|
self.add("gwscan/ROOT/default", "usr/lib/libc.so.7", "ELF-arm")
|
|
self.add("gwscan/ROOT/default", "etc/rc.conf", "text")
|
|
self.add("gwscan/ROOT/default", "empty", "")
|
|
for ds in self.DATASETS:
|
|
os.makedirs(os.path.join(self.ds, ds.replace("/", "_")), exist_ok=True)
|
|
fake = self.fx.make_fake
|
|
fake("mdconfig", 'case "$1" in -a) echo md7;; esac')
|
|
# export: "busy" the first FAKE_BUSY times
|
|
fake("zpool", """case "$1" in
|
|
import) exit ${FAKE_IMPORT_RC:-0};;
|
|
export) n=$(cat "$FAKE_LOG.busy" 2>/dev/null || echo 0); echo $((n + 1)) > "$FAKE_LOG.busy"
|
|
[ "$n" -ge "${FAKE_BUSY:-0}" ] || { echo "cannot export 'gwscan': pool is busy" >&2; exit 1; };;
|
|
esac""")
|
|
fake("sleep", "exit 0")
|
|
fake("zfs", 'cat "$FAKE_LISTING"')
|
|
# mount -t zfs -o ro DATASET DIR: the dataset's fixture tree appears at DIR
|
|
fake("mount", 'src="$FAKE_DS/$(echo "$5" | tr / _)"; [ -d "$src" ] || exit 1; cp -R "$src/." "$6/"')
|
|
fake("umount", 'find "$1" -mindepth 1 -delete')
|
|
fake("file", """[ "$1" = -N ] && shift
|
|
for f; do
|
|
case "$(head -c 7 "$f")" in
|
|
ELF-arm) echo "$f: ELF 64-bit LSB pie executable, ARM aarch64, for FreeBSD 14.3";;
|
|
ELF-x86) echo "$f: ELF 64-bit LSB executable, x86-64, for FreeBSD 14.3";;
|
|
*) echo "$f: ASCII text";;
|
|
esac
|
|
done""")
|
|
self.func = (build_function("die") + build_function("scan_image", [("/tmp/gwimage", f"{self.work}/gwimage")]))
|
|
|
|
def set_datasets(self, names):
|
|
with open(self.listing, "w") as f:
|
|
f.write("".join(n + "\n" for n in names))
|
|
|
|
def add(self, ds, rel, content):
|
|
p = os.path.join(self.ds, ds.replace("/", "_"), rel)
|
|
os.makedirs(os.path.dirname(p), exist_ok=True)
|
|
with open(p, "w") as f:
|
|
f.write(content)
|
|
|
|
def scan(self, released=True, **env):
|
|
e = {"PATH": f"{self.fx.bin}:/usr/bin:/bin", "FAKE_LOG": self.fx.log,
|
|
"FAKE_DS": self.ds, "FAKE_LISTING": self.listing}
|
|
e.update(env)
|
|
r = subprocess.run(["sh", "-c", 'set -eu; step() { echo ">>> $*"; }\n' + self.func + '\nscan_image "$1"',
|
|
"sh", "/images/OPNsense-26.1.11-arm-aarch64-GATEWAY.img"],
|
|
env=e, capture_output=True, text=True)
|
|
# the pool is let go of and nothing is left behind, whatever the outcome
|
|
calls = self.fx.calls()
|
|
if released:
|
|
self.assertIn("mdconfig -d -u md7", calls)
|
|
self.assertEqual(os.listdir(self.work), [])
|
|
return r, calls
|
|
|
|
def test_busy_pool_exported_once_free(self):
|
|
r, calls = self.scan(FAKE_BUSY="2")
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(calls.count("zpool export gwscan"), 3)
|
|
|
|
def test_pool_that_stays_busy(self):
|
|
r, calls = self.scan(released=False, FAKE_BUSY="100")
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertEqual(calls.count("zpool export gwscan"), 10)
|
|
self.assertIn("build.sh: cannot export the image's pool gwscan", r.stderr)
|
|
|
|
def test_clean_image(self):
|
|
r, calls = self.scan()
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertIn("zpool import -N -o readonly=on -R", "\n".join(calls))
|
|
self.assertIn("zpool export gwscan", calls)
|
|
mounted = [c.split()[5] for c in calls if c.startswith("mount ")]
|
|
self.assertEqual(mounted, self.DATASETS)
|
|
self.assertEqual(len([c for c in calls if c.startswith("umount ")]), len(self.DATASETS))
|
|
|
|
def test_foreign_elf_named_with_its_dataset(self):
|
|
self.add("gwscan/usr/home", "user/a.out", "ELF-x86")
|
|
r, calls = self.scan()
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("gwscan/usr/home:/user/a.out: ELF 64-bit LSB executable, x86-64", r.stderr)
|
|
self.assertIn("non-aarch64", r.stderr)
|
|
self.assertIn("zpool export gwscan", calls)
|
|
|
|
def test_foreign_elf_in_root(self):
|
|
self.add("gwscan/ROOT/default", "usr/local/bin/tool", "ELF-x86")
|
|
r, _ = self.scan()
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("gwscan/ROOT/default:/usr/local/bin/tool", r.stderr)
|
|
|
|
def test_firmware_blobs_allowed(self):
|
|
self.add("gwscan/ROOT/default", "boot/firmware/sdma.bin", "ELF-x86")
|
|
r, _ = self.scan()
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
|
|
def test_empty_root_fails(self):
|
|
# the failure this replaces: nothing mounted, nothing scanned, a clean pass
|
|
shutil.rmtree(os.path.join(self.ds, "gwscan_ROOT_default"))
|
|
os.makedirs(os.path.join(self.ds, "gwscan_ROOT_default"))
|
|
r, _ = self.scan()
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("no /bin/sh in gwscan/ROOT/default", r.stderr)
|
|
|
|
def test_no_root_dataset_fails(self):
|
|
self.set_datasets(["gwscan", "gwscan/usr", "gwscan/usr/home"])
|
|
r, _ = self.scan()
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("no /bin/sh in gwscan/ROOT/default", r.stderr)
|
|
|
|
def test_unmountable_dataset_fails(self):
|
|
self.set_datasets(self.DATASETS + ["gwscan/var"])
|
|
r, calls = self.scan()
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("cannot mount gwscan/var", r.stderr)
|
|
self.assertIn("zpool export gwscan", calls)
|
|
|
|
def test_import_failure(self):
|
|
r, calls = self.scan(FAKE_IMPORT_RC="1")
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("cannot import the image's pool", r.stderr)
|
|
self.assertFalse([c for c in calls if c.startswith("mount ")])
|
|
|
|
|
|
class ExitTrapTest(unittest.TestCase):
|
|
"""build.sh says when set -e stops it, but not again after die."""
|
|
|
|
def run_body(self, body):
|
|
with open(BUILD) as f:
|
|
trap = [ln for ln in f.read().splitlines() if ln.startswith("trap ")]
|
|
self.assertEqual(len(trap), 1)
|
|
return subprocess.run(["sh", "-c", "set -eu\n" + trap[0] + "\n" + build_function("die") + body],
|
|
capture_output=True, text=True)
|
|
|
|
def test_failed_command_reported(self):
|
|
r = self.run_body("false\necho not reached\n")
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertEqual(r.stdout, "")
|
|
self.assertEqual(r.stderr, "build.sh: stopped by a failed command (exit 1)\n")
|
|
|
|
def test_die_reported_once(self):
|
|
r = self.run_body('die "no set"\n')
|
|
self.assertEqual(r.returncode, 1)
|
|
self.assertEqual(r.stderr, "build.sh: no set\n")
|
|
|
|
def test_success_silent(self):
|
|
r = self.run_body("true\n")
|
|
self.assertEqual((r.returncode, r.stderr), (0, ""))
|
|
|
|
def test_usage_not_reported_as_failure(self):
|
|
r = subprocess.run(["sh", BUILD], capture_output=True, text=True)
|
|
self.assertEqual(r.returncode, 2)
|
|
self.assertNotIn("stopped by a failed command", r.stderr)
|
|
self.assertIn("build.sh build SERIES VERSION", r.stderr)
|
|
|
|
|
|
class CheckKernelBinTest(unittest.TestCase):
|
|
"""build.sh's check_kernel_bin: the kernel set must have the kernel U-Boot boots."""
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.mkdtemp(prefix="gw-kbin-")
|
|
self.addCleanup(shutil.rmtree, self.tmp)
|
|
self.func = build_function("die") + build_function("check_kernel_bin")
|
|
|
|
def kernel_set(self, *members):
|
|
src = os.path.join(self.tmp, "src")
|
|
for m in members:
|
|
os.makedirs(os.path.join(src, os.path.dirname(m)), exist_ok=True)
|
|
with open(os.path.join(src, m), "w") as f:
|
|
f.write("x")
|
|
path = os.path.join(self.tmp, "kernel-26.7.9-aarch64-GATEWAY.txz")
|
|
subprocess.run(["tar", "-C", src, "-cJf", path, "."], check=True)
|
|
return path
|
|
|
|
def check(self, path):
|
|
return subprocess.run(["sh", "-c", "set -eu\n" + self.func + '\ncheck_kernel_bin "$1"', "sh", path],
|
|
capture_output=True, text=True)
|
|
|
|
def test_with_kernel_bin(self):
|
|
r = self.check(self.kernel_set("boot/kernel/kernel", "boot/kernel/kernel.bin"))
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
|
|
def test_without_kernel_bin(self):
|
|
r = self.check(self.kernel_set("boot/kernel/kernel", "boot/kernel/if_dpaa.ko"))
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("kernel-26.7.9-aarch64-GATEWAY.txz has no boot/kernel/kernel.bin", r.stderr)
|
|
self.assertIn("WITH_KERNEL_BIN", r.stderr)
|
|
|
|
def test_kernel_bin_elsewhere(self):
|
|
r = self.check(self.kernel_set("boot/kernel/kernel", "boot/kernel.old/kernel.bin", "kernel.bin"))
|
|
self.assertNotEqual(r.returncode, 0)
|
|
|
|
def test_missing_set(self):
|
|
r = self.check(os.path.join(self.tmp, "nonexistent.txz"))
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("has no boot/kernel/kernel.bin", r.stderr)
|
|
|
|
def test_corrupt_set(self):
|
|
path = os.path.join(self.tmp, "kernel-26.7.9-aarch64-GATEWAY.txz")
|
|
with open(path, "wb") as f:
|
|
f.write(b"not a tar")
|
|
self.assertNotEqual(self.check(path).returncode, 0)
|
|
|
|
|
|
FAKE_CMM_C = r"""
|
|
#include <signal.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
|
|
/* stands in for cmm: daemonizes, writes its pid file, and on SIGTERM takes
|
|
a while to tear down before it removes the pid file and exits */
|
|
static volatile sig_atomic_t stop;
|
|
static void term(int sig) { (void)sig; stop = 1; }
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
(void)argc; (void)argv;
|
|
if (daemon(0, 0) != 0) return 1;
|
|
FILE *f = fopen(PIDFILE, "w");
|
|
if (f == NULL) return 1;
|
|
fprintf(f, "%d\n", (int)getpid());
|
|
fclose(f);
|
|
signal(SIGTERM, term);
|
|
while (!stop) pause();
|
|
sleep(2);
|
|
unlink(PIDFILE);
|
|
return 0;
|
|
}
|
|
"""
|
|
|
|
|
|
@unittest.skipUnless(os.path.exists("/etc/rc.subr") and shutil.which("cc"), "needs FreeBSD's rc.subr and cc")
|
|
class CmmRcTest(unittest.TestCase):
|
|
"""rc.d/cmm through FreeBSD's rc.subr, with a stand-in cmm."""
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.mkdtemp(prefix="gw-cmm-")
|
|
self.addCleanup(shutil.rmtree, self.tmp)
|
|
self.pidfile = os.path.join(self.tmp, "cmm.pid")
|
|
self.daemon = os.path.join(self.tmp, "cmm")
|
|
src = os.path.join(self.tmp, "cmm.c")
|
|
with open(src, "w") as f:
|
|
f.write(FAKE_CMM_C)
|
|
subprocess.run(["cc", f'-DPIDFILE="{self.pidfile}"', "-o", self.daemon, src], check=True)
|
|
with open(os.path.join(REPO, "rc.d", "cmm")) as f:
|
|
script = f.read()
|
|
for a, b in (('command="/usr/local/sbin/${name}"', f'command="{self.daemon}"'),
|
|
('pidfile="/var/run/${name}.pid"', f'pidfile="{self.pidfile}"'),
|
|
('start_precmd="cmm_prestart"', 'start_precmd=""')): # no cdx/fci here
|
|
self.assertIn(a, script)
|
|
script = script.replace(a, b)
|
|
self.rc = os.path.join(self.tmp, "rc.cmm")
|
|
with open(self.rc, "w") as f:
|
|
f.write(script)
|
|
self.addCleanup(self.kill_leftovers)
|
|
|
|
def kill_leftovers(self):
|
|
subprocess.run(["pkill", "-f", self.daemon], capture_output=True)
|
|
|
|
def run_rc(self, cmd):
|
|
return subprocess.run(["sh", self.rc, cmd], capture_output=True, text=True, timeout=60)
|
|
|
|
def running(self):
|
|
return subprocess.run(["pgrep", "-f", self.daemon], capture_output=True).returncode == 0
|
|
|
|
def test_start_status_stop(self):
|
|
r = self.run_rc("onestart")
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
for _ in range(50):
|
|
if os.path.exists(self.pidfile):
|
|
break
|
|
time.sleep(0.1)
|
|
self.assertTrue(self.running())
|
|
self.assertIn("is running as pid", self.run_rc("onestatus").stdout)
|
|
r = self.run_rc("onestop")
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
# stop returns only once cmm has exited, which takes it 2 seconds here
|
|
self.assertFalse(self.running(), r.stdout)
|
|
self.assertFalse(os.path.exists(self.pidfile))
|
|
self.assertNotEqual(self.run_rc("onestatus").returncode, 0)
|
|
|
|
def test_stale_pidfile_names_another_process(self):
|
|
other = subprocess.Popen(["sleep", "30"])
|
|
self.addCleanup(lambda: (other.kill(), other.wait()))
|
|
with open(self.pidfile, "w") as f:
|
|
f.write(f"{other.pid}\n")
|
|
r = self.run_rc("onestop")
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("not running", r.stdout + r.stderr)
|
|
self.assertIsNone(other.poll(), "stop killed a process that is not cmm")
|
|
|
|
|
|
class LockTest(unittest.TestCase):
|
|
"""build.sh's lock_check and lock_step: every checkout at its locked commit."""
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.mkdtemp(prefix="gw-lock-")
|
|
self.addCleanup(shutil.rmtree, self.tmp)
|
|
self.repo = os.path.join(self.tmp, "repo")
|
|
env = {"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t",
|
|
"GIT_COMMITTER_EMAIL": "t@t", "PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": self.tmp}
|
|
for cmd in (["git", "init", "-q", self.repo],
|
|
["git", "-C", self.repo, "commit", "-q", "--allow-empty", "-m", "x"]):
|
|
subprocess.run(cmd, check=True, env=env)
|
|
self.head = subprocess.run(["git", "-C", self.repo, "rev-parse", "HEAD"], check=True,
|
|
capture_output=True, text=True).stdout.strip()
|
|
self.lock = os.path.join(self.tmp, "lock-26.7.9")
|
|
self.func = build_function("die") + build_function("lock_check") + build_function("lock_step")
|
|
|
|
def run_lock(self, content, name="src", **env):
|
|
with open(self.lock, "w") as f:
|
|
f.write(content)
|
|
e = {"PATH": "/usr/bin:/bin:/usr/local/bin", "LOCK": self.lock, **env}
|
|
return subprocess.run(["sh", "-c", "set -eu\n" + self.func + '\nlock_step "$1" "$2"', "sh", name, self.repo],
|
|
env=e, capture_output=True, text=True)
|
|
|
|
def test_locked_commit(self):
|
|
r = self.run_lock(f"tools {'1' * 40}\nsrc {self.head}\n")
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertIn("locked commit", r.stdout)
|
|
|
|
def test_moved_ref(self):
|
|
r = self.run_lock(f"src {'a' * 40}\n")
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn(f"is at {self.head}, but lock-26.7.9 says {'a' * 40}", r.stderr)
|
|
|
|
def test_missing_entry(self):
|
|
r = self.run_lock(f"tools {self.head}\n")
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("must give exactly one commit for src", r.stderr)
|
|
|
|
def test_duplicate_entry(self):
|
|
r = self.run_lock(f"src {self.head}\nsrc {'b' * 40}\n")
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("exactly one commit", r.stderr)
|
|
|
|
def test_malformed_entries(self):
|
|
for content in (f"src {self.head[:12]}\n", f"src {self.head.upper()}\n", f"src {self.head}x\n",
|
|
f"srcx {self.head}\n", f"# src {self.head}\n", f"src\t{self.head} extra\n"):
|
|
with self.subTest(content=content):
|
|
self.assertNotEqual(self.run_lock(content).returncode, 0)
|
|
|
|
def test_name_is_not_a_prefix_match(self):
|
|
r = self.run_lock(f"src {self.head}\n", name="sr")
|
|
self.assertNotEqual(r.returncode, 0)
|
|
|
|
def test_tab_separated_and_trailing_space(self):
|
|
self.assertEqual(self.run_lock(f"src\t{self.head} \n").returncode, 0)
|
|
|
|
def test_write_mode_records(self):
|
|
out = os.path.join(self.tmp, "gwlock")
|
|
open(out, "w").close()
|
|
r = self.run_lock("", WRITE_LOCK=out)
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
with open(out) as f:
|
|
self.assertEqual(f.read(), f"src {self.head}\n")
|
|
|
|
def test_build_refuses_without_lock(self):
|
|
func = build_function("die") + build_function("step") + build_function("checkout_all")
|
|
deps = os.path.join(self.tmp, "deps")
|
|
os.makedirs(os.path.join(deps, "release"))
|
|
open(os.path.join(deps, "release", "build.sh"), "w").close()
|
|
r = subprocess.run(["sh", "-c", "set -eu\n" + func + "\ncheckout_all"],
|
|
env={"PATH": "/usr/bin:/bin", "DEPS": deps, "SERIES": "26.7", "VERSION": "26.7.9",
|
|
"LOCK": os.path.join(deps, "config", "lock-26.7.9")},
|
|
capture_output=True, text=True)
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("no config/lock-26.7.9: run build.sh lock 26.7 26.7.9", r.stderr)
|
|
|
|
|
|
class SignAuxRepoTest(unittest.TestCase):
|
|
"""build.sh's sign_aux_repo: the aux set's catalogue signed with KEYDIR's key."""
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.mkdtemp(prefix="gw-aux-")
|
|
self.addCleanup(shutil.rmtree, self.tmp)
|
|
self.fx = Fixture(self.tmp)
|
|
self.work = os.path.join(self.tmp, "work")
|
|
os.makedirs(self.work)
|
|
src = os.path.join(self.tmp, "src")
|
|
os.makedirs(os.path.join(src, "All"))
|
|
for name, data in (("All/rust-1.96.0.pkg", "rust"), ("packagesite.pkg", "unsigned"), (".abi_hint", "abi")):
|
|
with open(os.path.join(src, name), "w") as f:
|
|
f.write(data)
|
|
self.set = os.path.join(self.tmp, "aux-26.1.11-aarch64.tar")
|
|
subprocess.run(["tar", "-C", src, "-cf", self.set, "."], check=True)
|
|
# pkg repo DIR signing_command: CMD...: a catalogue naming its signing command
|
|
self.fx.make_fake("pkg", """[ "$1" = repo ] || exit 1
|
|
[ -z "${FAKE_PKG_FAIL:-}" ] || exit 1
|
|
dir=$2; shift 2
|
|
echo "signed by: $*" > "$dir/packagesite.pkg\"""")
|
|
self.func = (build_function("die") +
|
|
build_function("sign_aux_repo", [("/tmp/gwaux", f"{self.work}/gwaux")]))
|
|
|
|
def sign(self, set_=None, **env):
|
|
e = {"PATH": f"{self.fx.bin}:/usr/bin:/bin", "FAKE_LOG": self.fx.log, "KEYDIR": "/root/gwkey"}
|
|
e.update(env)
|
|
r = subprocess.run(["sh", "-c", 'set -eu; step() { echo ">>> $*"; }\n' + self.func + '\nsign_aux_repo "$1"',
|
|
"sh", set_ or self.set], env=e, capture_output=True, text=True)
|
|
self.assertEqual(os.listdir(self.work), [])
|
|
return r
|
|
|
|
def member(self, name):
|
|
return subprocess.run(["tar", "-xOf", self.set, name], capture_output=True, text=True, check=True).stdout
|
|
|
|
def test_catalogue_signed(self):
|
|
r = self.sign()
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(self.member("./packagesite.pkg"),
|
|
"signed by: signing_command: /usr/tools/scripts/pkg_sign.sh "
|
|
"/root/gwkey/repo.pub /root/gwkey/repo.key\n")
|
|
self.assertEqual(self.member("./All/rust-1.96.0.pkg"), "rust")
|
|
self.assertEqual(self.member("./.abi_hint"), "abi")
|
|
self.assertFalse(os.path.exists(self.set + ".new"))
|
|
|
|
def test_without_aux_set(self):
|
|
r = self.sign(set_=os.path.join(self.tmp, "none.tar"))
|
|
self.assertEqual((r.returncode, r.stdout), (0, ""))
|
|
self.assertEqual(self.fx.calls(), [])
|
|
|
|
def test_signing_failure_keeps_the_set(self):
|
|
with open(self.set, "rb") as f:
|
|
before = f.read()
|
|
r = self.sign(FAKE_PKG_FAIL="1")
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("build.sh: cannot sign the catalogue of", r.stderr)
|
|
with open(self.set, "rb") as f:
|
|
self.assertEqual(f.read(), before)
|
|
|
|
def test_broken_set(self):
|
|
with open(self.set, "wb") as f:
|
|
f.write(b"not a tar")
|
|
r = self.sign()
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("cannot sign the catalogue", r.stderr)
|
|
self.assertEqual(self.fx.calls(), [])
|
|
|
|
|
|
class ReleaseRepoTest(unittest.TestCase):
|
|
"""build.sh's release_repo: FreeBSD's ports repository pinned to this release."""
|
|
|
|
# /etc/pkg/FreeBSD.conf of the official images
|
|
CONF_14 = """# $FreeBSD$
|
|
#
|
|
# To disable this repository, instead of modifying or removing this file,
|
|
# create a /usr/local/etc/pkg/repos/FreeBSD.conf file:
|
|
#
|
|
# mkdir -p /usr/local/etc/pkg/repos
|
|
# echo "FreeBSD: { enabled: no }" > /usr/local/etc/pkg/repos/FreeBSD.conf
|
|
#
|
|
|
|
FreeBSD: {
|
|
url: "pkg+https://pkg.FreeBSD.org/${ABI}/quarterly",
|
|
mirror_type: "srv",
|
|
signature_type: "fingerprints",
|
|
fingerprints: "/usr/share/keys/pkg",
|
|
enabled: yes
|
|
}
|
|
"""
|
|
CONF_15 = """#
|
|
# echo "FreeBSD-ports: { enabled: no }" > /usr/local/etc/pkg/repos/FreeBSD.conf
|
|
#
|
|
|
|
FreeBSD-ports: {
|
|
url: "pkg+https://pkg.FreeBSD.org/${ABI}/quarterly",
|
|
mirror_type: "srv",
|
|
signature_type: "fingerprints",
|
|
fingerprints: "/usr/share/keys/pkg",
|
|
enabled: yes
|
|
}
|
|
FreeBSD-ports-kmods: {
|
|
url: "pkg+https://pkg.FreeBSD.org/${ABI}/kmods_quarterly_${VERSION_MINOR}",
|
|
mirror_type: "srv",
|
|
enabled: yes
|
|
}
|
|
FreeBSD-base: {
|
|
url: "pkg+https://pkg.FreeBSD.org/${ABI}/base_release_${VERSION_MINOR}",
|
|
enabled: no
|
|
}
|
|
"""
|
|
|
|
def repo(self, conf, version):
|
|
with tempfile.NamedTemporaryFile("w", suffix=".conf", delete=False) as f:
|
|
f.write(conf)
|
|
self.addCleanup(os.unlink, f.name)
|
|
func = build_function("die") + build_function("release_repo")
|
|
return subprocess.run(["sh", "-c", func + '\nrelease_repo "$1" "$2"', "sh", f.name, version],
|
|
capture_output=True, text=True)
|
|
|
|
def test_freebsd_14(self):
|
|
r = self.repo(self.CONF_14, "14.3-RELEASE-p6")
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(r.stdout, 'FreeBSD: { url: "pkg+https://pkg.FreeBSD.org/${ABI}/release_3", mirror_type: "srv" }\n')
|
|
|
|
def test_freebsd_15_ports_repository(self):
|
|
r = self.repo(self.CONF_15, "15.1-RELEASE-p7")
|
|
self.assertEqual(r.returncode, 0, r.stderr)
|
|
self.assertEqual(r.stdout,
|
|
'FreeBSD-ports: { url: "pkg+https://pkg.FreeBSD.org/${ABI}/release_1", mirror_type: "srv" }\n')
|
|
|
|
def test_no_repository(self):
|
|
r = self.repo("# nothing\n", "15.1-RELEASE")
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("no repository in", r.stderr)
|
|
|
|
def test_unexpected_version(self):
|
|
for bad in ("", "15", "CURRENT", "15.x-RELEASE", "1;id"):
|
|
with self.subTest(bad):
|
|
r = self.repo(self.CONF_15, bad)
|
|
self.assertNotEqual(r.returncode, 0)
|
|
self.assertIn("unexpected FreeBSD version", r.stderr)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|