v0.2.0 — pre-beta: per-MAC bindings, /metrics, themes, animated forge

This is the bulk pre-beta cleanup pass. Bumps the workspace to 0.2.0.
Test count is 56 -> 66 (+10), clippy is fully clean across the
workspace (was several dozen warnings).

## New features

**Per-MAC host bindings** (Tinkerbell smee pattern). New
`HostBindings` registry maps a MAC -> preferred boot target, persisted
to <work_dir>/hosts.json. The DHCP reply now embeds `?mac=${mac}` in
the boot.ipxe URL; iPXE substitutes the literal MAC client-side, so
the HTTP layer can short-circuit straight to the bound target instead
of rendering the menu. Reserved menu shortcuts (`_local`, `_gate`,
`_tools_menu`) are valid targets too. New /api/hosts CRUD + a Hosts
tab in the sidebar.

**Prometheus `/metrics`** endpoint. Tiny lock-free implementation —
just AtomicU64s and a Display impl, no `prometheus` / `metrics-rs`
dep. Counters: DHCP replies (per arch label), DHCP declined, TFTP
transfers (per status), TFTP bytes, HTTP requests (per route).
Gauges: ISO count, client count, gate count, gate-imaging, NFS active
mounts, uptime, build info. Plain text exposition format,
text/plain;version=0.0.4 content-type, no auth (all metric values are
non-sensitive counts).

**Light + dark themes**. CSS tokens on `:root` and
`:root[data-theme=light]`, swap by toggle button (top-right) or `T`
hotkey. Persisted in localStorage; pre-paint inline script avoids
dark<->light flash. Light palette designed against the Netbox Labs
reference screenshot — near-white surfaces, soft grey dividers,
accent unchanged for brand consistency. Terminal pane stays dark in
both themes (it's a console, that's the right read).

**Animated SVG logo + forge widget**. New `logo.svg` is a refined
silver/grey anvil. New `anvil-forge.svg` adds rising sparks and a
pulsing underglow via SMIL — pure SVG, no GIF, no JS animation loop.
Used:
  - in the **forge progress** widget on Dashboard + Forge Gate, paired
    with a `linear-gradient(warn -> accent)` bar with a moving sheen;
    goes idle (greyscale, no sheen) at zero imaging load
  - in the page-load `<div class=loader>` that replaces the old
    "Loading..." text

## Code cleanup pass

`cargo clippy --workspace --all-targets` is now warning-free. Spot
fixes across the tree:
  - `format!()`-into-`String` -> `std::fmt::Write::write!`
  - manual reverse comparators -> `Reverse`
  - `map_or(false, ...)` -> `is_some_and`
  - redundant closures -> method references
  - `r#"..."#` raw strings without `"` -> `r"..."`
  - `std::io::Error::new(Other, ...)` -> `Error::other`
  - `as i32` on `c.id()` -> `cast_signed()`
  - merged identical match arms

## Windows workflow validation

New integration test synthesizes an ISO9660 with the SOURCES\\BOOT.WIM
sentinel, uploads it, asserts:
  1. introspection labels it `windows_pe` with has_boot_wim=true,
  2. the boot entry is `BootKind::Wimboot` with all five canonical
     files (bootmgr, bootmgr.efi, bcd, boot.sdi, boot.wim),
  3. the rendered iPXE script chains wimboot with `initrd --name`
     entries for each file, and
  4. NO trust-store strings appear in the rendered output: bcdedit,
     testsigning, certutil, httpdisk, and test-signed are all
     explicitly forbidden as a hard guarantee.

WinPE bootstrap (startnet.cmd) picks up the Bootimus v0.1.58 lessons:
explicit `net start Workstation` before `net use` to avoid the SMB
client lazy-init race, and surfaces errors instead of blind retries.

## Docs

architecture.md gains a "Phase 5" section explaining the host-bindings
+ metrics + theming + Windows-test work, plus a refreshed "deferred
to Phase 6" list (real-hardware integration, autounattend library,
distro profile manifest, WoL trigger, syslog receiver, IPv6).
README updates the status line, the "what it does" list, and adds
the new Hosts/Terminal tab names.
This commit is contained in:
Miles Ward
2026-04-30 02:28:10 -04:00
parent a9c4f408a9
commit 49d0b00a8a
31 changed files with 1651 additions and 209 deletions
+1 -1
View File
@@ -98,7 +98,7 @@ pub fn introspect(path: &Path) -> IntrospectionReport {
// that happens in the store after introspection.
let (k, i) = guess_kernel_initrd(report.family);
report.kernel_path = k.map(str::to_string);
report.initrd_paths = i.iter().map(|s| s.to_string()).collect();
report.initrd_paths = i.iter().map(std::string::ToString::to_string).collect();
report
}
+18 -10
View File
@@ -87,13 +87,17 @@ impl SmbManager {
/// Write out `smb.conf` for the currently-discovered shares. Safe to
/// call while smbd is running — smbd reloads on SIGHUP.
pub fn write_conf(&self) -> std::io::Result<Vec<String>> {
use std::fmt::Write as _;
std::fs::create_dir_all(&self.smb_dir)?;
let shares = self.discover_shares();
let mut conf = String::new();
conf.push_str(SMB_CONF_GLOBAL);
for name in &shares {
let path = self.smb_dir.join(name);
conf.push_str(&format!(
// Per-share block. `write!` to String never fails — the unwrap
// is provably unreachable, but expect() makes that explicit.
write!(
conf,
"\n[{name}]\n\
path = {}\n\
comment = PXEForge Windows install media ({name})\n\
@@ -103,7 +107,8 @@ impl SmbManager {
browseable = yes\n\
available = yes\n",
path.display(),
));
)
.expect("writing to a String is infallible");
}
let tmp = self.conf_path.with_extension("conf.tmp");
std::fs::write(&tmp, conf)?;
@@ -114,7 +119,7 @@ impl SmbManager {
/// Start smbd. No-op if already running.
pub fn start(&self) -> SmbState {
let mut g = self.child.lock();
if g.as_ref().map_or(false, |c| c.id() > 0) {
if g.as_ref().is_some_and(|c| c.id() > 0) {
return self.state.lock().clone();
}
if !smbd_present() {
@@ -173,7 +178,10 @@ impl SmbManager {
}
};
if let Some(c) = g.as_mut() {
let pid = c.id() as i32;
// u32 -> i32 for libc::kill. We never spawn enough children
// for the pid to overflow i32; cast_signed makes the intent
// explicit and silences the lint.
let pid = c.id().cast_signed();
// SAFETY: libc::kill is FFI-safe; we pass a pid we own (returned
// from `Child::id` above, the child is alive because we hold the
// Mutex guard `g`) and a well-defined signal constant. Return
@@ -211,7 +219,7 @@ fn smbd_present() -> bool {
false
}
const SMB_CONF_GLOBAL: &str = r#"[global]
const SMB_CONF_GLOBAL: &str = r"[global]
workgroup = PXEFORGE
server min protocol = SMB2
smb ports = 445
@@ -227,7 +235,7 @@ lock directory = /tmp
state directory = /tmp
cache directory = /tmp
pid directory = /tmp
"#;
";
/// Extract a Windows ISO at `iso_path` into `smb_dir/<slug>/`. Uses
/// `7z` when available (most reliable for UDF + ISO9660 hybrid images);
@@ -271,10 +279,10 @@ pub fn extract_windows_iso(iso_path: &Path, smb_dir: &Path, slug: &str) -> std::
.arg(&target)
.output()?;
if out.status.success() { return Ok(target); }
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("bsdtar failed: {}", String::from_utf8_lossy(&out.stderr)),
));
return Err(std::io::Error::other(format!(
"bsdtar failed: {}",
String::from_utf8_lossy(&out.stderr)
)));
}
Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
+12 -12
View File
@@ -19,9 +19,10 @@ use tokio::io::AsyncWriteExt;
/// `Nfs` entries point at a file inside a remote share that the
/// `NfsManager` is keeping mounted. We resolve the on-disk path lazily
/// in [`IsoStore::iso_path_for`] using the `nfs_root` set at startup.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum IsoSource {
#[default]
Local,
Nfs {
mount_id: String,
@@ -30,12 +31,6 @@ pub enum IsoSource {
},
}
impl Default for IsoSource {
fn default() -> Self {
Self::Local
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IsoMeta {
/// Stable slug used in URLs (derived from the uploaded filename).
@@ -156,7 +151,11 @@ impl IsoStore {
while let Some(e) = entries.next_entry().await? {
let p = e.path();
if p.extension().and_then(|s| s.to_str()) != Some("json") { continue; }
if !p.file_name().and_then(|s| s.to_str()).map_or(false, |n| n.ends_with(".meta.json")) {
if !p
.file_name()
.and_then(|s| s.to_str())
.is_some_and(|n| n.ends_with(".meta.json"))
{
continue;
}
if let Ok(text) = tokio::fs::read_to_string(&p).await {
@@ -218,7 +217,8 @@ impl IsoStore {
pub fn list(&self) -> Vec<IsoMeta> {
let g = self.inner.read();
let mut v: Vec<_> = g.isos.values().cloned().collect();
v.sort_by(|a, b| b.uploaded_at.cmp(&a.uploaded_at));
// Newest-first by upload time.
v.sort_by_key(|m| std::cmp::Reverse(m.uploaded_at));
v
}
@@ -403,9 +403,9 @@ fn linux_cmdline(family: DistroFamily, id: &str) -> String {
DistroFamily::OpenSuse => format!(
"install={iso_url} netsetup=dhcp"
),
DistroFamily::Arch => format!(
"archiso_http_srv=${{base-url}}/iso/ archisobasedir=arch ip=dhcp copytoram"
),
DistroFamily::Arch => {
"archiso_http_srv=${base-url}/iso/ archisobasedir=arch ip=dhcp copytoram".to_string()
}
DistroFamily::Alpine => format!(
"alpine_repo=${{base-url}}/iso/{id}/ modloop=${{base-url}}/iso/{id}/boot/modloop-lts ip=dhcp"
),
+22 -5
View File
@@ -152,18 +152,35 @@ const WINPESHL_INI: &str = "[LaunchApps]\r\n\
/// Uses CRLF line endings because WinPE cmd.exe requires them for .cmd files
/// created on unix hosts.
fn render_startnet(host: &str, share: &str) -> String {
let mut s = String::new();
use std::fmt::Write as _;
let host = host.trim();
let share = share.trim_matches('/');
let mut s = String::new();
// Windows-style CRLF; consumed verbatim by cmd.exe inside WinPE.
// Bootimus v0.1.58 lesson: surface `net use` errors instead of
// tight-looping on a blind retry. We retry but log every miss.
s.push_str("@echo off\r\n");
s.push_str("echo PXEForge WinPE bootstrap\r\n");
s.push_str("wpeinit\r\n");
// v0.1.58: explicitly start Workstation before mapping the share —
// `net use` otherwise lazily inits SMB-client and races wpeinit.
s.push_str("net start Workstation >nul 2>&1\r\n");
s.push_str("ipconfig /renew\r\n");
s.push_str(&format!("echo Waiting for SMB server {host} to be reachable...\r\n"));
s.push_str(&format!(":waitsmb\r\nping -n 1 -w 500 {host} >nul && goto havenet\r\ntimeout /t 2 /nobreak >nul\r\ngoto waitsmb\r\n"));
writeln!(s, "echo Waiting for SMB server {host} to be reachable...\r").unwrap();
writeln!(
s,
":waitsmb\r\nping -n 1 -w 500 {host} >nul && goto havenet\r\n\
timeout /t 2 /nobreak >nul\r\ngoto waitsmb\r"
)
.unwrap();
s.push_str(":havenet\r\n");
s.push_str(&format!("echo Mapping install media from \\\\{host}\\{share}...\r\n"));
s.push_str(&format!(":mapshare\r\nnet use Z: \\\\{host}\\{share} /user:guest \"\" /persistent:no && goto mapped\r\ntimeout /t 3 /nobreak >nul\r\ngoto mapshare\r\n"));
writeln!(s, "echo Mapping install media from \\\\{host}\\{share}...\r").unwrap();
writeln!(
s,
":mapshare\r\nnet use Z: \\\\{host}\\{share} /user:guest \"\" /persistent:no && goto mapped\r\n\
timeout /t 3 /nobreak >nul\r\ngoto mapshare\r"
)
.unwrap();
s.push_str(":mapped\r\n");
s.push_str("echo Starting Windows Setup\r\n");
s.push_str("Z:\\setup.exe\r\n");