Keep OPNsense telemetry when the script worker cannot start and build it for FreeBSD 14.1

A worker linked on the FreeBSD 15 test guest needs FBSD_1.9 and does not load on
OPNsense 24.7; the agent then retried the job session every 30 s and never sent a
heartbeat or inventory. The agent now pauses script capabilities for an hour and
reconnects without them. tools/dev_opnsense_worker.py links the worker against the
official FreeBSD 14.1 pkgbase libraries. The installer checks that the worker loads
before binding it and reports success only after a heartbeat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 12:17:34 +01:00
co-authored by Claude Opus 5.5
parent 19163a2efe
commit 93429e4394
8 changed files with 216 additions and 15 deletions
+5
View File
@@ -6,6 +6,11 @@ mod root;
fn main() -> anyhow::Result<()> { fn main() -> anyhow::Result<()> {
match std::env::args().nth(1).as_deref() { match std::env::args().nth(1).as_deref() {
Some("--root-helper") => root::serve(), Some("--root-helper") => root::serve(),
// Loader check for installers: resolves every symbol against this system's libc.
Some("--version") => {
println!("{}", env!("CARGO_PKG_VERSION"));
Ok(())
}
Some("--root-capabilities") => { Some("--root-capabilities") => {
println!("{}", serde_json::to_string(&root::caps()?)?); println!("{}", serde_json::to_string(&root::caps()?)?);
Ok(()) Ok(())
@@ -138,6 +138,16 @@ def bind_jobs(meta, host, port):
os.fsync(f.fileno()) os.fsync(f.fileno())
def worker_starts():
"""The native worker must load on this FreeBSD release; resolve all symbols now."""
try:
res = subprocess.run([str(APP / 'rmm-opnsense-jobs'), '--version'], capture_output=True, timeout=15,
env={**os.environ, 'LD_BIND_NOW': '1'})
except OSError:
return False
return res.returncode == 0
def running(): def running():
return all(Path(f'/var/run/discovery-{part}.pid').is_file() for part in ('agent', 'collect')) return all(Path(f'/var/run/discovery-{part}.pid').is_file() for part in ('agent', 'collect'))
@@ -175,24 +185,32 @@ def main():
if res.returncode: if res.returncode:
stop('Die Aufnahme beim Server ist fehlgeschlagen. Bitte einen neuen Einmalcode erzeugen.') stop('Die Aufnahme beim Server ist fehlgeschlagen. Bitte einen neuen Einmalcode erzeugen.')
print('Gerät beim Server aufgenommen.') print('Gerät beim Server aufgenommen.')
if (APP / 'rmm-opnsense-jobs').is_file() and not BINDING.exists(): worker = (APP / 'rmm-opnsense-jobs').is_file()
if worker and not worker_starts():
worker = False
print('Hinweis: Der Skript-Worker startet auf dieser OPNsense-Version nicht. '
'Inventur und Heartbeat laufen, Skripte sind bis zu einem passenden Paket nicht verfügbar.')
if worker and not BINDING.exists():
bind_jobs(meta, host, port) bind_jobs(meta, host, port)
print('Skriptausführung für diese Installation gebunden.') print('Skriptausführung für diese Installation gebunden.')
before = device_view(host, port) if existing else None before = device_view(host, port)
generation = int(before['installed']['connection_generation']) if before else -1 generation = int(before['installed']['connection_generation']) if before else -1
contact = before['installed'].get('last_contact_at') if before else None
subprocess.run(['service', 'discovery_agent', 'restart' if running() else 'start'], check=True, subprocess.run(['service', 'discovery_agent', 'restart' if running() else 'start'], check=True,
stdout=subprocess.DEVNULL) stdout=subprocess.DEVNULL)
for _ in range(30): for _ in range(30):
time.sleep(3) time.sleep(3)
view = running() and device_view(host, port) view = running() and device_view(host, port)
# A new client hello raises the connection generation and reports the installed version. # A new client hello raises the connection generation and reports the installed version;
# only a heartbeat after it (new last contact) shows that telemetry actually flows.
if (view and view['installed'].get('agent_version') == meta['version'] if (view and view['installed'].get('agent_version') == meta['version']
and int(view['installed']['connection_generation']) > generation): and int(view['installed']['connection_generation']) > generation
and view['installed'].get('last_contact_at') not in (None, contact)):
print(f'Fertig. Das Gerät meldet sich mit Version {view["installed"]["agent_version"]} ' print(f'Fertig. Das Gerät meldet sich mit Version {view["installed"]["agent_version"]} '
'und erscheint in der WebUI unter Geräte.') 'und erscheint in der WebUI unter Geräte.')
return return
stop('Der Dienst läuft, hat sich aber noch nicht beim Server gemeldet. ' stop('Der Dienst läuft, sendet aber keinen Heartbeat. '
'Diagnose: /var/log/system/latest.log und service discovery_agent restart.') 'Diagnose: grep discovery-agent /var/log/system/latest.log | tail')
if __name__ == '__main__': if __name__ == '__main__':
+6 -2
View File
@@ -10,11 +10,15 @@ Unter **Verwaltung → Geräteaufnahme** den Kunden wählen und einen Einmalcode
fetch -o opnsense.sh 'https://discovery.ease-technologies.de:8443/install/opnsense.sh' && sh opnsense.sh 'https://discovery.ease-technologies.de:8443' fetch -o opnsense.sh 'https://discovery.ease-technologies.de:8443/install/opnsense.sh' && sh opnsense.sh 'https://discovery.ease-technologies.de:8443'
``` ```
Das Skript fragt nach dem **Einmalcode**. Es lädt mit diesem Code das OPNsense-Paket des Servers, prüft jede Datei gegen Größe und SHA-256 und installiert es mit denselben Schritten wie [install-dev.sh](install-dev.sh). Danach nimmt es die Firewall unter dem Dienstkonto `discovery` auf. Ist der Skript-Worker im Paket, wird er über den Gerätekanal an genau diese Installation gebunden (`job-binding.json`). Das Skript startet den Dienst und wartet, bis sich die Firewall mit der Paketversion meldet. [Installer](../../crates/server/src/bootstrap/opnsense_install.py) Das Skript fragt nach dem **Einmalcode**. Es lädt mit diesem Code das OPNsense-Paket des Servers, prüft jede Datei gegen Größe und SHA-256 und installiert es mit denselben Schritten wie [install-dev.sh](install-dev.sh). Danach nimmt es die Firewall unter dem Dienstkonto `discovery` auf. Ist der Skript-Worker im Paket, prüft das Skript zuerst, ob er auf diesem System lädt (`rmm-opnsense-jobs --version` mit `LD_BIND_NOW=1`), und bindet ihn dann über den Gerätekanal an genau diese Installation (`job-binding.json`). Lädt er nicht, meldet das Skript das und legt keine Bindung an. Das Skript startet den Dienst und meldet erst Erfolg, wenn die Firewall sich mit der Paketversion verbunden und danach einen Heartbeat gesendet hat. [Installer](../../crates/server/src/bootstrap/opnsense_install.py)
Ein erneuter Lauf auf einer aufgenommenen Firewall aktualisiert nur die Programmdateien. Geräteidentität, Zertifikat, Journale und Bindung bleiben erhalten; der Einmalcode wird dabei nicht verbraucht. Gehört die vorhandene Bindung zu einem anderen Kunden, bricht das Skript ab. Für einen Kundenwechsel das Gerät neu aufnehmen. Den Root-Helper richtet der Installer nicht ein (siehe unten). Ein erneuter Lauf auf einer aufgenommenen Firewall aktualisiert nur die Programmdateien. Geräteidentität, Zertifikat, Journale und Bindung bleiben erhalten; der Einmalcode wird dabei nicht verbraucht. Gehört die vorhandene Bindung zu einem anderen Kunden, bricht das Skript ab. Für einen Kundenwechsel das Gerät neu aufnehmen. Den Root-Helper richtet der Installer nicht ein (siehe unten).
**Paket bereitstellen:** `python3 tools/dev_opnsense_bundle.py --worker-from-guest` baut `agent.pyz` und `collect.pyz` aus diesem Verzeichnis, nimmt das rc.d-Skript und den nativen Worker aus dem Testgast und legt alles mit `manifest.json` unter `devstate/mvp-releases/config/opnsense/` auf dem Entwicklungsserver ab (Eigentümer wie die übrige Releasekonfiguration, Modus 0600). Die Version stammt aus `VERSION` in `agent.py`. Ohne gültiges Paket zeigt die WebUI keinen OPNsense-Befehl. Das Paket ist nicht signiert. Seine Integrität beruht auf der HTTPS-Verbindung zum Installationsserver, über die auch das Skript selbst kommt. [Paketwerkzeug](../../tools/dev_opnsense_bundle.py) Startet der Worker im laufenden Betrieb nicht (Meldung `job worker unavailable; scripts paused, telemetry continues` im Systemlog), verbindet sich der Agent nach 30 Sekunden ohne Skriptfähigkeiten neu. Heartbeat und Inventur laufen weiter, Skripte sind für eine Stunde ausgesetzt. Danach versucht der Agent den Worker erneut.
**Worker bauen:** `python3 tools/dev_opnsense_worker.py OUT` baut `rmm-opnsense-jobs` im Testgast, linkt ihn aber gegen die Basisbibliotheken von FreeBSD 14.1 (OPNsense 24.7, offizielles `base.txz`, gegen das Release-MANIFEST geprüft). Ein nativ auf dem FreeBSD-15-Testgast gelinkter Worker verlangt `FBSD_1.9` aus der libc und lädt auf OPNsense 24.x nicht. [Worker-Werkzeug](../../tools/dev_opnsense_worker.py)
**Paket bereitstellen:** `python3 tools/dev_opnsense_bundle.py --worker OUT` baut `agent.pyz` und `collect.pyz` aus diesem Verzeichnis, nimmt das rc.d-Skript und den gebauten Worker und legt alles mit `manifest.json` unter `devstate/mvp-releases/config/opnsense/` auf dem Entwicklungsserver ab (Eigentümer wie die übrige Releasekonfiguration, Modus 0600). Die Version stammt aus `VERSION` in `agent.py`. Ohne gültiges Paket zeigt die WebUI keinen OPNsense-Befehl. Das Paket ist nicht signiert. Seine Integrität beruht auf der HTTPS-Verbindung zum Installationsserver, über die auch das Skript selbst kommt. [Paketwerkzeug](../../tools/dev_opnsense_bundle.py)
## Quelle und Entwicklungsinstallation ## Quelle und Entwicklungsinstallation
+14 -4
View File
@@ -20,9 +20,13 @@ STATE = Path('/var/db/discovery-agent')
CA = '/usr/local/etc/discovery-agent/ca.pem' CA = '/usr/local/etc/discovery-agent/ca.pem'
HOST = 'discovery.ease-technologies.de' HOST = 'discovery.ease-technologies.de'
MEDIA = 'application/x-protobuf' MEDIA = 'application/x-protobuf'
VERSION = '0.1.0-opnsense.6' VERSION = '0.1.0-opnsense.7'
WORKER = Path('/usr/local/libexec/discovery-agent/rmm-opnsense-jobs') WORKER = Path('/usr/local/libexec/discovery-agent/rmm-opnsense-jobs')
BINDING = Path('/usr/local/etc/discovery-agent/job-binding.json') BINDING = Path('/usr/local/etc/discovery-agent/job-binding.json')
# A worker that cannot start (e.g. built for a newer FreeBSD) must not stop
# heartbeat and inventory. Script capabilities pause until this moment.
WORKER_RETRY = 3600
worker_paused_until = 0.0
def post(ctx, path, data, media): def post(ctx, path, data, media):
@@ -177,11 +181,12 @@ def session(db, identity, boot, instance):
def run_channel(db, identity, boot, instance, stack): def run_channel(db, identity, boot, instance, stack):
global worker_paused_until
ctx = context() ctx = context()
ctx.load_cert_chain(STATE/'device.pem', STATE/'device.key') ctx.load_cert_chain(STATE/'device.pem', STATE/'device.key')
generation = 0 generation = 0
jobs = None jobs = None
enabled = BINDING.is_file() and WORKER.is_file() enabled = BINDING.is_file() and WORKER.is_file() and time.monotonic() >= worker_paused_until
def send(kind, payload, captured=None): def send(kind, payload, captured=None):
# A lost inventory ACK replays the exact durable envelope, including its # A lost inventory ACK replays the exact durable envelope, including its
@@ -249,8 +254,13 @@ def run_channel(db, identity, boot, instance, stack):
p.stdout.close() p.stdout.close()
stack.callback(close) stack.callback(close)
jobs = Jobs(p) jobs = Jobs(p)
if jobs.read()!=b'ready': try:
raise ValueError('job worker unavailable') ready = jobs.read()==b'ready'
except ValueError:
ready = False
if not ready:
worker_paused_until = time.monotonic()+WORKER_RETRY
raise ValueError('job worker unavailable; scripts paused, telemetry continues')
last = None last = None
previous = None previous = None
check_cert = time.monotonic()+12*3600 check_cert = time.monotonic()+12*3600
+41
View File
@@ -76,5 +76,46 @@ class Reconnect(unittest.TestCase):
self.assertEqual(captures[0],captures[1]) self.assertEqual(captures[0],captures[1])
def test_broken_worker_pauses_scripts_but_keeps_heartbeat(self):
with tempfile.TemporaryDirectory() as temp:
db = sqlite3.connect(':memory:')
db.executescript('CREATE TABLE sequence(id INTEGER PRIMARY KEY,n INTEGER);INSERT INTO sequence VALUES(1,0);'
'CREATE TABLE pending(id INTEGER PRIMARY KEY,envelope BLOB,observed INTEGER);')
worker = Path(temp)/'worker'
# Same effect as a loader failure: exits before printing "ready".
worker.write_text('#!/bin/sh\nexit 1\n')
worker.chmod(0o755)
binding = Path(temp)/'binding.json'
binding.write_text('{}')
seen = []
def gateway(_ctx,path,data,media):
req = a.pb.MessageBatch.FromString(data).messages[0]
reply = a.pb.Envelope()
reply.CopyFrom(req)
kind = req.WhichOneof('payload')
seen.append((kind, list(req.client_hello.capabilities)))
if kind == 'client_hello':
reply.connection_generation = len(seen)
reply.server_hello.CopyFrom(a.pb.ServerHello(connection_generation=len(seen),max_message_bytes=1024*1024))
else:
reply.ack.CopyFrom(a.pb.Ack(message_id=req.message_id))
return a.pb.MessageBatch(protocol_major=1,messages=[reply]).SerializeToString()
with patch.object(a,'context'), patch.object(a,'renew',return_value=False), \
patch.object(a,'post',gateway), patch.object(a,'WORKER',worker), patch.object(a,'BINDING',binding), \
patch.object(a,'worker_paused_until',0.0), \
patch.object(a,'usage',return_value=(a.pb.SystemUsage(),[])), \
patch.object(a.time,'clock_gettime',return_value=100), \
patch.object(a.time,'CLOCK_UPTIME',1,create=True), patch.object(a.time,'sleep',side_effect=StopIteration):
identity = {'agent_id':str(uuid.uuid4()),'asset_id':str(uuid.uuid4())}
with self.assertRaisesRegex(ValueError,'telemetry continues'):
a.session(db,identity,str(uuid.uuid4()),str(uuid.uuid4()))
with self.assertRaises(StopIteration):
a.session(db,identity,str(uuid.uuid4()),str(uuid.uuid4()))
self.assertEqual([k for k,_ in seen],['client_hello','client_hello','heartbeat'])
self.assertIn('run_script',seen[0][1])
self.assertEqual(seen[1][1],['heartbeat/1','opnsense.base/1'])
if __name__=='__main__': if __name__=='__main__':
unittest.main() unittest.main()
+1 -1
View File
@@ -11,7 +11,7 @@
| Genehmigung und Zustellung | [Genehmigungseingang](../crates/server/src/approvals.rs), [Entscheidung und Freigabe](../crates/server/src/jobs.rs), [Gerätegateway](../crates/server/src/job_gateway.rs), [Abgleich im Agenten](../crates/agent-core/src/reconcile.rs) | | Genehmigung und Zustellung | [Genehmigungseingang](../crates/server/src/approvals.rs), [Entscheidung und Freigabe](../crates/server/src/jobs.rs), [Gerätegateway](../crates/server/src/job_gateway.rs), [Abgleich im Agenten](../crates/agent-core/src/reconcile.rs) |
| MCP und Administrator-Skripte | [Werkzeuge](../crates/server/src/mcp.rs), [Tokenrechte](../crates/server/src/mcp_tokens.rs), [Helper und zentrale Geräteregel](../crates/server/src/managed_scripts.rs) | | MCP und Administrator-Skripte | [Werkzeuge](../crates/server/src/mcp.rs), [Tokenrechte](../crates/server/src/mcp_tokens.rs), [Helper und zentrale Geräteregel](../crates/server/src/managed_scripts.rs) |
| Geräteaufnahme und Releasewechsel | [HTTPS-Installer und Lebenszyklus](../crates/server/src/bootstrap), [Releasekatalog](../crates/server/src/agent_updates.rs), [Signaturprüfung](../crates/updater/src/manifest.rs) | | Geräteaufnahme und Releasewechsel | [HTTPS-Installer und Lebenszyklus](../crates/server/src/bootstrap), [Releasekatalog](../crates/server/src/agent_updates.rs), [Signaturprüfung](../crates/updater/src/manifest.rs) |
| OPNsense-Aufnahme per HTTPS | [Skript](../crates/server/src/bootstrap/opnsense.sh), [Installer](../crates/server/src/bootstrap/opnsense_install.py), [Paketauslieferung](../crates/server/src/bootstrap/opnsense.rs), [Paketwerkzeug](../tools/dev_opnsense_bundle.py) | | OPNsense-Aufnahme per HTTPS | [Skript](../crates/server/src/bootstrap/opnsense.sh), [Installer](../crates/server/src/bootstrap/opnsense_install.py), [Paketauslieferung](../crates/server/src/bootstrap/opnsense.rs), [Paketwerkzeug](../tools/dev_opnsense_bundle.py), [Worker-Build für FreeBSD 14.1](../tools/dev_opnsense_worker.py) |
| Native Laufzeiten | [Linux-Agent](../crates/agent/src/main.rs), [Linux-Inventar und Skripte](../crates/agent-linux/src), [Windows-Agent](../crates/agent-windows/src/runtime.rs), [Agentprotokoll](../proto/BACKEND_CONTRACT.md) | | Native Laufzeiten | [Linux-Agent](../crates/agent/src/main.rs), [Linux-Inventar und Skripte](../crates/agent-linux/src), [Windows-Agent](../crates/agent-windows/src/runtime.rs), [Agentprotokoll](../proto/BACKEND_CONTRACT.md) |
| Proxmox-Host und VM-Zuordnung | [Sammelmodul](../crates/agent-linux/src/inventory/proxmox.rs), [Validierung und Backupbewertung](../crates/domain/src/inventory_document/proxmox.rs), [automatische Zuordnung](../crates/server/src/proxmox_links.sql), [Detailansicht](../web/src/proxmox.tsx), [Betrieb](../deploy/proxmox/README.md) | | Proxmox-Host und VM-Zuordnung | [Sammelmodul](../crates/agent-linux/src/inventory/proxmox.rs), [Validierung und Backupbewertung](../crates/domain/src/inventory_document/proxmox.rs), [automatische Zuordnung](../crates/server/src/proxmox_links.sql), [Detailansicht](../web/src/proxmox.tsx), [Betrieb](../deploy/proxmox/README.md) |
+3 -2
View File
@@ -2,7 +2,8 @@
"""Build the OPNsense agent bundle and place it on the dev server for the HTTPS installer. """Build the OPNsense agent bundle and place it on the dev server for the HTTPS installer.
The bundle is `agent.pyz`, `collect.pyz`, the rc.d script and optionally the native The bundle is `agent.pyz`, `collect.pyz`, the rc.d script and optionally the native
script worker `rmm-opnsense-jobs` (FreeBSD amd64, built natively in the test guest). script worker `rmm-opnsense-jobs` (FreeBSD amd64, built with tools/dev_opnsense_worker.py
against FreeBSD 14.1 so that it also loads on OPNsense 24.x).
It lands in `devstate/mvp-releases/config/opnsense/` next to the Linux bootstrap It lands in `devstate/mvp-releases/config/opnsense/` next to the Linux bootstrap
configuration and is served only against a valid one-time enrollment code. configuration and is served only against a valid one-time enrollment code.
""" """
@@ -68,7 +69,7 @@ def main():
worker = parser.add_mutually_exclusive_group() worker = parser.add_mutually_exclusive_group()
worker.add_argument('--worker', type=Path, help='Native rmm-opnsense-jobs (FreeBSD amd64) to include') worker.add_argument('--worker', type=Path, help='Native rmm-opnsense-jobs (FreeBSD amd64) to include')
worker.add_argument('--worker-from-guest', action='store_true', worker.add_argument('--worker-from-guest', action='store_true',
help='Take the installed rmm-opnsense-jobs from the OPNsense test guest') help='Take the installed rmm-opnsense-jobs from the OPNsense test guest (loads only on the guest release)')
parser.add_argument('--prepare-only', type=Path, metavar='DIR', help='Write the bundle locally, do not upload') parser.add_argument('--prepare-only', type=Path, metavar='DIR', help='Write the bundle locally, do not upload')
args = parser.parse_args() args = parser.parse_args()
version = re.search(r"^VERSION = '([A-Za-z0-9._-]+)'$", (ROOT / 'deploy/opnsense/agent.py').read_text(), re.M)[1] version = re.search(r"^VERSION = '([A-Za-z0-9._-]+)'$", (ROOT / 'deploy/opnsense/agent.py').read_text(), re.M)[1]
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""Build the native OPNsense script worker `rmm-opnsense-jobs` for the oldest supported release.
The build runs in the OPNsense test guest (toolchain `/opt/discovery-rust`), but links
against the FreeBSD 14.1 base libraries (OPNsense 24.7) instead of the guest's own
FreeBSD. A worker linked natively on FreeBSD 15 needs `FBSD_1.9` from libc and does
not load on OPNsense 24.x. The sysroot consists of the official pkgbase packages of
14.1 (`pkg.freebsd.org/FreeBSD:14:amd64/base_release_1`), each checked against the
SHA-256 of the repository catalogue, and is kept in `/var/tmp/fbsd141` on the guest.
Usage: python3 tools/dev_opnsense_worker.py OUT_FILE
Then: python3 tools/dev_opnsense_bundle.py --worker OUT_FILE
"""
import argparse
import hashlib
import io
import json
from pathlib import Path
import shlex
import subprocess
import tarfile
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
CREDENTIALS = ROOT / 'credentials'
SSH = ['ssh', '-F', '/dev/null', '-T', '-i', str(CREDENTIALS / 'opnsense-dev-key'),
'-o', 'UserKnownHostsFile=' + str(CREDENTIALS / 'opnsense-dev.known_hosts'),
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
'-o', 'IdentitiesOnly=yes', '-o', 'ConnectTimeout=10', '-o', 'ServerAliveInterval=30', 'root@192.168.247.1']
REPO = 'https://pkg.freebsd.org/FreeBSD:14:amd64/base_release_1'
PACKAGES = {'FreeBSD-clibs', 'FreeBSD-clibs-dev', 'FreeBSD-runtime', 'FreeBSD-runtime-dev',
'FreeBSD-libexecinfo', 'FreeBSD-libexecinfo-dev', 'FreeBSD-libcompiler_rt-dev',
# libprocstat, libmemstat, libdevstat (linked by Rust std on FreeBSD)
'FreeBSD-utilities', 'FreeBSD-utilities-dev'}
SYSROOT = '/var/tmp/fbsd141/root'
SOURCE = '/root/discovery-stage/worker-src'
def packages():
"""(file, sha256) of the 14.1 library packages from the HTTPS repository catalogue."""
with urllib.request.urlopen(REPO + '/packagesite.pkg', timeout=60) as res:
raw = res.read(16 * 1024 * 1024)
# zstd-compressed tar; the system tar knows the format.
site = subprocess.run(['tar', '--zstd', '-xOf', '-', 'packagesite.yaml'], input=raw, check=True,
capture_output=True).stdout.decode()
found = [json.loads(line) for line in site.splitlines() if line.strip()]
found = [(d['repopath'], d['sum']) for d in found if d['name'] in PACKAGES and d['version'].startswith('14.1')]
if len(found) != len(PACKAGES):
raise SystemExit('pkgbase 14.1: nicht alle Bibliothekspakete im Katalog')
return found
def stamp_of(found):
return ' '.join(sorted(name for name, _ in found))
def sysroot(found):
"""Download on the notebook (the guest's own network is unreliable), verify, unpack in the guest."""
stamp = stamp_of(found)
current = subprocess.run([*SSH, 'cat /var/tmp/fbsd141/stamp'], capture_output=True).stdout.decode().strip()
if current == stamp:
return
# Packages carry schg flags (libc, init); the sysroot is plain data without them.
subprocess.run([*SSH, 'sh -s'], check=True, input=(
'set -eu\nif [ -d /var/tmp/fbsd141 ]; then chflags -R noschg /var/tmp/fbsd141; rm -rf /var/tmp/fbsd141; fi\n'
f'mkdir -p {SYSROOT}\n').encode())
for name, digest in found:
with urllib.request.urlopen(REPO + '/' + name, timeout=120) as res:
data = res.read(128 * 1024 * 1024)
if hashlib.sha256(data).hexdigest() != digest:
raise SystemExit(f'{name}: Prüfsumme stimmt nicht mit dem Katalog überein')
target = shlex.quote('/var/tmp/fbsd141/' + name)
subprocess.run([*SSH, f'cat >{target}'], input=data, check=True)
subprocess.run([*SSH, 'sh -s'], check=True, input=(
f'set -eu\n[ "$(sha256 -q {target})" = {digest} ]\n'
f'tar -xf {target} -C {SYSROOT} --no-fflags --exclude "+*" 2>/dev/null || true\nrm {target}\n').encode())
subprocess.run([*SSH, 'sh -s'], check=True, input=(
f'set -eu\n[ -f {SYSROOT}/usr/lib/crt1.o ] && [ -f {SYSROOT}/lib/libc.so.7 ]\n'
f'echo {shlex.quote(stamp)} >/var/tmp/fbsd141/stamp\n').encode())
BUILD = f"""set -eu
cd {SOURCE}
export PATH=/opt/discovery-rust/bin:$PATH CARGO_TARGET_DIR=/var/tmp/opnsense-worker-target
export RUST_LIBC_UNSTABLE_FREEBSD_VERSION=14 CC=clang CFLAGS="--sysroot={SYSROOT}"
export RUSTFLAGS="-C linker=clang -C link-arg=--sysroot={SYSROOT} -C link-arg=-fuse-ld=lld"
cargo build --locked --release -p rmm-opnsense-jobs >&2
bin=$CARGO_TARGET_DIR/release/rmm-opnsense-jobs
if readelf -V "$bin" | grep -q 'FBSD_1\\.9'; then echo 'worker still needs FBSD_1.9' >&2; exit 1; fi
cat "$bin"
"""
def source_tar():
files = subprocess.run(['git', 'ls-files', '-z', '--', 'Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml',
'proto', 'crates'], cwd=ROOT, check=True, capture_output=True).stdout.split(b'\0')
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode='w') as tar:
for name in filter(None, files):
path = ROOT / name.decode()
if path.is_file():
tar.add(path, arcname=name.decode())
return buf.getvalue()
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('out', type=Path)
args = parser.parse_args()
sysroot(packages())
subprocess.run([*SSH, f'rm -rf {SOURCE} && mkdir -p {SOURCE}'], check=True)
subprocess.run([*SSH, f'tar -xf - -C {SOURCE}'], input=source_tar(), check=True)
binary = subprocess.run([*SSH, 'sh -s'], input=BUILD.encode(), capture_output=True)
if not binary.stdout.startswith(b'\x7fELF'):
raise SystemExit(binary.stderr.decode()[-2000:])
args.out.write_bytes(binary.stdout)
args.out.chmod(0o755)
print(f'{args.out}: {len(binary.stdout)} bytes, linked against FreeBSD 14.1')
if __name__ == '__main__':
main()