build(node): package NetBird and JK BMS with pinned shared UI sources

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:43:00 +03:00
parent f3d0c25ccd
commit df743a9f6c
15 changed files with 378 additions and 20 deletions
+18 -3
View File
@@ -11,8 +11,8 @@ import sys
ROOT = Path(__file__).resolve().parents[1]
BINARY_VERSION = "0.8.49"
VERSION = "0.8.49-94"
BINARY_VERSION = "0.8.53"
VERSION = "0.8.53-111"
sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging"))
from debian import package
@@ -44,7 +44,7 @@ Architecture: amd64
Maintainer: NODE.DC local build <noreply@example.invalid>
Section: admin
Priority: optional
Depends: adduser, systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), python3-gi, gir1.2-gtk-3.0, gir1.2-webkit2-4.1, pkexec, polkitd, ca-certificates, hicolor-icon-theme, network-manager, iproute2, wireguard-tools, python3-psycopg2, postgresql-16 (>= 16.15), timescaledb-2-oss-postgresql-16 (= 2.29.2~ubuntu24.04-1615), udev, usbutils, libc6 (>= 2.39), libstdc++6 (>= 12), libgcc-s1, zlib1g
Depends: adduser, systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), python3-gi, python3-dbus, bluez (>= 5.72), gir1.2-gtk-3.0, gir1.2-webkit2-4.1, pkexec, polkitd, ca-certificates, hicolor-icon-theme, network-manager, iproute2, wireguard-tools, python3-psycopg2, postgresql-16 (>= 16.15), timescaledb-2-oss-postgresql-16 (= 2.29.2~ubuntu24.04-1615), udev, usbutils, libc6 (>= 2.39), libstdc++6 (>= 12), libgcc-s1, zlib1g
Description: Mission Core onboard computer configuration
Local graphical setup, host inventory, SSH access and persistent node identity.
""".encode()
@@ -53,6 +53,20 @@ Description: Mission Core onboard computer configuration
files = [("usr/lib/mission-core-node/node-agent", payload, 0o755)]
files.append(("usr/lib/mission-core-node/wireguard_helper.py", (ROOT.parent / "wireguard-client/helper.py").read_bytes(), 0o644))
files.append(("usr/lib/systemd/system/mission-core-node-wireguard.service", (p / "mission-core-node-wireguard.service").read_bytes(), 0o644))
netbird = ROOT.parents[1] / "src/k1link/fleet/netbird"
for name in ("client.py", "assets.py", "persistence.py", "clients.lock.json"):
files.append(("usr/lib/mission-core-node/netbird/" + name, (netbird / name).read_bytes(), 0o644))
files.append(("usr/lib/mission-core-node/netbird/__init__.py", b"", 0o644))
lock = json.loads((netbird / "clients.lock.json").read_text())
row = next(item for item in lock["items"] if item["id"] == "linux-amd64")
data = (ROOT / "build/netbird" / row["filename"]).read_bytes()
if len(data) != row["bytes"] or hashlib.sha256(data).hexdigest() != row["sha256"]:
raise ValueError("Bundled NetBird package changed")
files.append(("usr/share/mission-core-node/netbird/" + row["filename"], data, 0o644))
files.append(("usr/share/mission-core-node/netbird/clients.lock.json", (netbird / "clients.lock.json").read_bytes(), 0o644))
for name in ("netbird_helper.py", "netbird_install.py"):
files.append(("usr/lib/mission-core-node/" + name, (p / name).read_bytes(), 0o644))
files.append(("usr/lib/systemd/system/mission-core-node-netbird.service", (p / "mission-core-node-netbird.service").read_bytes(), 0o644))
brand = (ROOT.parents[2] / "NODEDC_DESIGN_GUIDELINE/apps/catalog/public/nodedc-mark.svg").read_bytes()
files.append(("usr/share/icons/hicolor/scalable/apps/org.nodedc.MissionCoreNode.svg", desktop_icon(brand), 0o644))
for source, path, mode in [
@@ -126,6 +140,7 @@ Description: Mission Core onboard computer configuration
import runpy
files.extend(runpy.run_path(str(ROOT.parents[1] / "plugins/vesc/packaging/payload.py"))["payload"]())
files.extend(runpy.run_path(str(ROOT.parents[1] / "plugins/usb-can/packaging/payload.py"))["payload"]())
files.extend(runpy.run_path(str(ROOT.parents[1] / "plugins/jk-bms/packaging/payload.py"))["payload"]())
archive = package(controls, files)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(archive)
@@ -15,7 +15,7 @@ sys.path.insert(0, str(REPO / "scripts/packaging"))
from build_retention import input_hold, publish_input # noqa: E402
DG = REPO.parent / "NODEDC_DESIGN_GUIDELINE"
DG_COMMIT = "a6e6c8f2d9c3de8d98b60c30da6a70d9538c1ef2"
DG_COMMIT = "972944e6f234eaaa24cd73543f9f1eef871f24c8"
USB_CAN_SDK_SHA256 = "3f4681c64b086ecd4bf538908e09ed5203a05286632c0d99485b88f9b069285c"
@@ -40,7 +40,10 @@ def build(qualified, node_only=False, base=None):
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=DG, text=True).strip()
if commit != DG_COMMIT:
raise ValueError("Design Guideline revision differs from the admitted source")
paths = list(files(REPO))
# Operator-only media (including large rover models) is not consumed by
# Node's separate Vite public directory. Keep it in full Core builds only.
paths = [path for path in files(REPO)
if not (node_only and path.is_relative_to(REPO / "apps/control-station/public"))]
# Build DG from its own pinned workspace lock. Its generated dist and
# transitive dependencies are not copied from a developer installation.
paths += [
@@ -78,6 +81,13 @@ def build(qualified, node_only=False, base=None):
# board, runtime path override or operator compiler dependency is needed.
virtual = str(REPO.name + "/apps/node-agent/build/model-packages/" + package_name)
entries[virtual] = qualified
netbird_lock = json.loads((REPO / "src/k1link/fleet/netbird/clients.lock.json").read_text())
row = next(item for item in netbird_lock["items"] if item["id"] == "linux-amd64")
vendor = NODE / "build/netbird" / row["filename"]
data = vendor.read_bytes()
if len(data) != row["bytes"] or hashlib.sha256(data).hexdigest() != row["sha256"]:
raise ValueError("Pinned NetBird payload changed")
entries[str(vendor.relative_to(REPO.parent))] = vendor
native_root = REPO / "plugins/vesc"
native = json.loads((native_root / "packaging/native-runtime.json").read_text())
native_path = native_root / "build/native-runtime" / native["file"]
@@ -105,7 +115,7 @@ def build(qualified, node_only=False, base=None):
for name, path in entries.items():
data = path.read_bytes()
if len(data) > 100 * 1024 * 1024:
raise ValueError("Source file exceeds the artifact bound")
raise ValueError(f"Source file exceeds the artifact bound: {name}")
metadata[name] = {
"bytes": len(data),
"sha256": hashlib.sha256(data).hexdigest(),
@@ -219,6 +219,10 @@ def tailscale_install():
return "Tailscale установлен; системная служба запущена. Вход проверяется отдельно."
def netbird_install():
return command(["/usr/bin/python3", "-I", "-B", "/usr/lib/mission-core-node/netbird_install.py"], timeout=660).strip()
def desktop_autostart():
owned_config(Path('/usr/share/mission-core-node/mission-core-node-autostart.desktop'),
Path('/etc/xdg/autostart/org.nodedc.MissionCoreNode.desktop'))
@@ -245,7 +249,7 @@ def usb_startup():
OPERATIONS = {"platform": platform, "packages": packages, "node-service": node_service,
"desktop-autostart": desktop_autostart, "usb-startup": usb_startup,
"network-inventory": network_inventory, "usb-inventory": usb_inventory,
"ssh-service": ssh_service, "tailscale-install": tailscale_install}
"ssh-service": ssh_service, "tailscale-install": tailscale_install, "netbird-install": netbird_install}
def run_steps(profile, operations, save):
@@ -23,6 +23,7 @@ NODE_DEPENDENCIES = ('timescaledb-2-loader-postgresql-16_2.29.2~ubuntu24.04-1615
ROOT = Path("/var/tmp/mission-core-node-installs")
SERVICES = (
"mission-core-node.service",
"mission-core-jk-bms.service",
"mission-core-vesc.service",
"mission-core-usb-can.service",
"mission-core-k1.service",
@@ -331,6 +332,7 @@ def main():
"node-service",
["/usr/bin/systemctl", "is-active", "--quiet", "mission-core-node.service"],
)
run("bms-service", ["/usr/bin/systemctl", "is-active", "--quiet", "mission-core-jk-bms.service"])
run("wireguard-service", ["/usr/bin/systemctl", "is-active", "--quiet", "mission-core-node-wireguard.service"])
run("wireguard-socket", ["/usr/bin/python3", "-I", "-c",
'import socket,json; s=socket.socket(socket.AF_UNIX); s.settimeout(5); s.connect("/run/mission-core-wireguard/control.sock"); s.sendall(b\'{"action":"health"}\\n\'); r=json.loads(s.makefile("rb").readline(16385)); assert r.get("ok") is True and r["result"]["schema"]=="missioncore.wireguard-helper/v1"; print("WireGuard helper ready")'])
+10
View File
@@ -109,6 +109,16 @@ class NodeApplication(Gtk.Application):
if not local_url(self.view.get_uri() or ""):
return
action = result.get_js_value().to_string()
if action.startswith("{") and len(action) <= 4096:
try:
payload = json.loads(action)
uri = payload.get("url", "")
parsed = urlsplit(uri)
if payload.get("action") == "netbird-login" and parsed.scheme == "https" and parsed.hostname and not parsed.username and not parsed.password and parsed.path.startswith("/oauth2/"):
Gio.AppInfo.launch_default_for_uri(uri, None)
except (ValueError, TypeError, AttributeError, GLib.Error):
pass
return
if action == "authorize":
self.login()
elif action == "configure-system":
+3 -1
View File
@@ -246,6 +246,8 @@ def main():
*[str(node / "internal/node" / name) for name in (
"link_budget.go", "link_budget_test.go", "rover_channel.go",
"rover_local_delivery.go", "rover_local_delivery_test.go", "rover_diagnostics.go",
"inventory.go", "network_inventory.go", "network_inventory_test.go",
"network_hardware.go", "network_hardware_test.go",
"rover_diagnostics_lane.go", "rover_link.go", "rover_stream_state.go", "server.go")],
str(node / "cmd/node-agent/main.go"),
],
@@ -263,7 +265,7 @@ def main():
run("node-environment-tests", ["/usr/bin/python3", "-m", "unittest", "test_environment_helper", "test_wifi_latency_trial", "test_usb_startup_recovery", "test_desktop_startup", "test_install_owner_release", "test_can_maintenance", "test_vesc_hall_recovery", "test_owner_dependencies", "test_build_source_reuse", "-v"], cwd=node / "packaging")
run("owner-release-staging-tests", ["/usr/bin/python3", "plugins/insta360-x4/packaging/test_owner_release_entry.py"], cwd=repo)
run("node-usb-unit-validation", ["/usr/bin/systemd-analyze", "verify", str(node / "packaging/mission-core-node-usb-startup.service"), str(node / "packaging/mission-core-node-wifi-trial.service")], cwd=node)
run("node-usb-unit-validation", ["/usr/bin/systemd-analyze", "verify", str(node / "packaging/mission-core-node-usb-startup.service"), str(node / "packaging/mission-core-node-wifi-trial.service"), str(node / "packaging/mission-core-node-netbird.service")], cwd=node)
run("vesc-reader-tests", ["/usr/bin/python3", "-m", "unittest", "discover", "-s", "plugins/vesc/tests", "-v"], cwd=repo)
run("usb-can-native-abi", ["/usr/bin/python3", "-B", "-c",
"from runtime.sdk import library; library('build/sdk/libcontrolcanfd.so'); print('Pinned SDK loaded; no USB open')"],
@@ -0,0 +1,29 @@
[Unit]
Description=Mission Core onboard NetBird connection adapter
After=network-online.target netbird.service
Before=mission-core-node.service
[Service]
ExecStart=/usr/bin/python3 -I -B /usr/lib/mission-core-node/netbird_helper.py
Restart=on-failure
RestartSec=3
StateDirectory=mission-core-netbird
StateDirectoryMode=0700
# The vendor CLI mirrors its active profile under XDG_CONFIG_HOME even when
# talking to the daemon. Keep that bookkeeping inside our writable state,
# while /root and operator homes remain inaccessible.
Environment=XDG_CONFIG_HOME=/var/lib/mission-core-netbird/config
RuntimeDirectory=mission-core-netbird
RuntimeDirectoryMode=0755
UMask=0077
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
CapabilityBoundingSet=CAP_CHOWN CAP_DAC_OVERRIDE
MemoryMax=96M
TasksMax=24
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,69 @@
"""Root adapter: only the authenticated Node service may manage its own client."""
import json
import os
import pwd
import socket
import socketserver
import struct
import sys
from pathlib import Path
# Installed, root-owned sources from the same revision as Core. No third-party Python deps.
sys.path.insert(0, str(Path(__file__).resolve().parent))
from netbird.client import Client
SOCKET = Path("/run/mission-core-netbird/control.sock")
def dispatch(client, body):
if not isinstance(body, dict):
raise ValueError("Некорректный запрос.")
action = body.get("action")
if action == "status" and set(body) == {"action"}:
return client.status()
if action == "cancel" and set(body) == {"action"}:
return client.cancel()
if action == "connect" and set(body) <= {"action", "server_url", "setup_key"}:
return client.connect(body.get("server_url", ""), body.get("setup_key", ""))
raise ValueError("Неизвестное действие.")
class Handler(socketserver.StreamRequestHandler):
def handle(self):
self.connection.settimeout(20)
_, uid, _ = struct.unpack(
"3i", self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)
)
if uid != self.server.uid:
return
try:
raw = self.rfile.readline(4097)
if len(raw) > 4096 or not raw.endswith(b"\n"):
return
result = {"ok": True, "result": dispatch(self.server.client, json.loads(raw))}
except ValueError as error:
result = {"ok": False, "error": str(error)}
except Exception:
result = {"ok": False, "error": "Служба NetBird недоступна. Повторите подключение."}
self.wfile.write(json.dumps(result).encode() + b"\n")
def main():
os.umask(0o077)
user = pwd.getpwnam("mission-core-node")
SOCKET.unlink(missing_ok=True)
# Serial requests bound concurrency; connect/cancel themselves are non-blocking.
with socketserver.UnixStreamServer(str(SOCKET), Handler) as server:
server.uid = user.pw_uid
server.client = Client(Path("/var/lib/mission-core-netbird"))
os.chown(SOCKET, 0, user.pw_gid)
os.chmod(SOCKET, 0o660)
try:
server.serve_forever()
finally:
server.client.close()
if __name__ == "__main__":
main()
@@ -0,0 +1,79 @@
"""Versioned Ubuntu 24.04/amd64 preparation. Bundled, pinned vendor package only."""
import hashlib
import json
import os
import subprocess
from pathlib import Path
ROOT = Path("/usr/share/mission-core-node/netbird")
def install():
system = dict(
line.split("=", 1)
for line in Path("/etc/os-release").read_text().splitlines()
if "=" in line
)
if (
system.get("ID", "").strip('"') != "ubuntu"
or system.get("VERSION_ID", "").strip('"') != "24.04"
or os.uname().machine != "x86_64"
):
raise ValueError("NetBird подготовлен для Ubuntu 24.04 amd64.")
lock = json.loads((ROOT / "clients.lock.json").read_text())
item = next(row for row in lock["items"] if row["id"] == "linux-amd64")
package = ROOT / item["filename"]
with package.open("rb") as stream:
if (
package.stat().st_size != item["bytes"]
or hashlib.file_digest(stream, "sha256").hexdigest() != item["sha256"]
):
raise ValueError("Пакет NetBird повреждён.")
current = subprocess.run(
["/usr/bin/dpkg-query", "-W", "-f=${Version}\t${db:Status-Status}", "netbird"],
capture_output=True,
text=True,
)
if current.returncode == 0 and current.stdout.strip().split("\t")[0] != lock["version"]:
raise ValueError(
"Установлена другая версия NetBird. Сохраните её настройки перед обновлением."
)
if current.returncode or not current.stdout.strip().endswith("\tinstalled"):
subprocess.run(
["/usr/bin/apt-get", "-y", "--no-remove", "install", str(package)],
check=True,
timeout=600,
env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "DEBIAN_FRONTEND": "noninteractive"},
capture_output=True,
)
subprocess.run(
[
"/usr/bin/systemctl",
"enable",
"--now",
"netbird.service",
"mission-core-node-netbird.service",
],
check=True,
timeout=45,
capture_output=True,
)
subprocess.run(
[
"/usr/bin/systemctl",
"is-active",
"--quiet",
"netbird.service",
"mission-core-node-netbird.service",
],
check=True,
timeout=10,
)
return "NetBird установлен. Выберите сервер и способ входа в разделе «Частная сеть»."
if __name__ == "__main__":
if os.geteuid() != 0:
raise SystemExit("Use environment preparation")
print(install())
@@ -5,8 +5,8 @@
<action id="org.nodedc.mission-core-node.configure-system">
<description>Configure the Mission Core Node environment</description>
<description xml:lang="ru">Настроить окружение Mission Core Node</description>
<message>Install required packages, configure Node and SSH services, collect system inventory and install Tailscale.</message>
<message xml:lang="ru">Установить зависимости, настроить службы БК и SSH, проверить сеть и USB, установить Tailscale. Вход и ключи подтверждаются отдельно.</message>
<message>Install required packages, configure Node and SSH services, collect system inventory and install Tailscale and NetBird.</message>
<message xml:lang="ru">Установить зависимости, настроить службы БК и SSH, проверить сеть и USB, установить Tailscale и NetBird. Вход и ключи подтверждаются отдельно.</message>
<defaults><allow_any>no</allow_any><allow_inactive>no</allow_inactive><allow_active>auth_admin</allow_active></defaults>
<annotate key="org.freedesktop.policykit.exec.path">/usr/lib/mission-core-node/configure-system</annotate>
</action>
+8
View File
@@ -9,10 +9,18 @@ case "$1" in
if ! getent passwd mission-core-sensors >/dev/null; then
adduser --system --group --home /var/lib/mission-core-sensors --no-create-home --disabled-login mission-core-sensors
fi
if ! getent passwd mission-core-jk-bms >/dev/null; then
adduser --system --group --home /var/lib/mission-core-jk-bms --no-create-home --disabled-login mission-core-jk-bms
fi
# Only bootstrap required to open the GUI. Operational configuration is a
# versioned job started by «Настройка окружения → Сконфигурировать».
if [ -d /run/systemd/system ]; then
systemctl daemon-reload
systemctl reload dbus.service
systemctl enable mission-core-jk-bms.service
systemctl restart mission-core-jk-bms.service
systemctl enable mission-core-node-netbird.service
systemctl restart mission-core-node-netbird.service
systemctl enable mission-core-node-wireguard.service
systemctl restart mission-core-node-wireguard.service
systemctl enable mission-core-node.service
+4
View File
@@ -70,6 +70,9 @@ if [ "$1" = upgrade ] && [ -n "${2:-}" ] && dpkg --compare-versions "$2" lt 0.8.
fi
case "$1" in
upgrade|remove|deconfigure)
if [ -d /run/systemd/system ] && [ -f /usr/lib/systemd/system/mission-core-jk-bms.service ]; then
systemctl disable --now mission-core-jk-bms.service
fi
if [ -d /run/systemd/system ] && [ -f /usr/lib/systemd/system/mission-core-vesc.service ]; then
systemctl disable --now mission-core-vesc.service
fi
@@ -129,5 +132,6 @@ fi
if [ "$1" = remove ] || { [ "$1" = upgrade ] && [ -n "${2:-}" ] && dpkg --compare-versions "$2" lt 0.8.49-91; }; then
if [ -d /run/systemd/system ]; then
systemctl disable --now mission-core-node-wireguard.service || true
systemctl disable --now mission-core-node-netbird.service || true
fi
fi