Compare commits
15
Commits
795f80a44c
...
v0.115.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0873d2c79d | ||
|
|
12a11edfd7 | ||
|
|
71ab5a957c | ||
|
|
f6c740bc24 | ||
|
|
968173095e | ||
|
|
63c603d919 | ||
|
|
fdb9bedb03 | ||
|
|
4be4750aae | ||
|
|
165b11bda3 | ||
|
|
e83bb8d2f1 | ||
|
|
c0a647237a | ||
|
|
9c49fa91af | ||
|
|
fbeb6dc328 | ||
|
|
8180f4ff80 | ||
|
|
9155c55d4c |
@@ -11,7 +11,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: alkane-verify
|
||||
runs-on: alkane-ci
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
permissions:
|
||||
|
||||
@@ -7,7 +7,7 @@ on:
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: alkane-verify
|
||||
runs-on: alkane-ci
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
permissions:
|
||||
|
||||
@@ -11,7 +11,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: alkane-fast
|
||||
runs-on: alkane-ci
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
env:
|
||||
|
||||
@@ -11,7 +11,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: alkane-verify
|
||||
runs-on: alkane-ci
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
outputs:
|
||||
@@ -195,8 +195,73 @@ jobs:
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
|
||||
# The Windows build of each change is validated on the main release run
|
||||
# (build-test-release / windows-native), not on the PR gate: it is a full
|
||||
# mingw + Wine cross-build that roughly doubled PR wall-clock. PRs verify Linux
|
||||
# (clippy, build, tests, self-test) fast; Windows is still built and shipped at
|
||||
# release, so a Windows-only break surfaces on the merge to main.
|
||||
# The Windows build of the same change (main's release gate, run on the PR):
|
||||
# clippy for the Windows target, the release .exe, every unit test under
|
||||
# Wine, and the headless UI self-test under Wine. Only for changes that can
|
||||
# affect the binary (the "full" surface).
|
||||
verify-windows:
|
||||
needs: verify
|
||||
if: needs.verify.outputs.surface == 'full'
|
||||
runs-on: alkane-ci
|
||||
container:
|
||||
image: gitea.bluefla.re/blueflare/alkane-ci@sha256:4929b2979851f1f12fb8f92ef74236ae4c2ea735a41ead94a16af416a4f0a1a5
|
||||
env:
|
||||
CARGO_TARGET_DIR: target
|
||||
CARGO_BUILD_JOBS: 2
|
||||
WX_WINDOWS_PREFIX: /root/.cache/wx-3.3.3-mingw
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install Windows toolchain
|
||||
run: bash ci/windows-ci.sh toolchain
|
||||
|
||||
- name: Configure bounded Rust compiler cache
|
||||
run: bash ci/configure-rust-cache.sh
|
||||
|
||||
- name: Compute wxMSW cache key
|
||||
id: wx-key
|
||||
run: bash ci/wx-cache-key.sh windows
|
||||
|
||||
- name: Check prebuilt wxMSW
|
||||
id: wx-image
|
||||
run: bash ci/check-wx-image-prefix.sh windows
|
||||
|
||||
- name: Cache vendored wxMSW build
|
||||
if: steps.wx-image.outputs.available != 'true'
|
||||
id: wx-cache
|
||||
uses: actions/cache/restore@v4
|
||||
continue-on-error: true
|
||||
with:
|
||||
path: /root/.cache/wx-3.3.3-mingw
|
||||
key: ${{ steps.wx-key.outputs.key }}
|
||||
|
||||
- name: Build wxMSW (once, then cached)
|
||||
id: wx-build
|
||||
run: bash ci/ensure-wx-prefix.sh windows
|
||||
|
||||
- name: Save vendored wxMSW build
|
||||
if: steps.wx-cache.outputs.cache-hit != 'true' && steps.wx-build.outputs.built == 'true'
|
||||
uses: actions/cache/save@v4
|
||||
continue-on-error: true
|
||||
with:
|
||||
path: /root/.cache/wx-3.3.3-mingw
|
||||
key: ${{ steps.wx-key.outputs.key }}
|
||||
|
||||
- name: Clippy (Windows target, warnings are errors)
|
||||
run: bash ci/windows-ci.sh clippy
|
||||
|
||||
- name: Build (Windows)
|
||||
run: bash ci/windows-ci.sh build
|
||||
|
||||
- name: Unit tests (Windows build, under Wine)
|
||||
run: bash ci/windows-ci.sh test
|
||||
|
||||
- name: Headless UI self-test (Windows build, under Wine)
|
||||
run: bash ci/windows-ci.sh selftest
|
||||
|
||||
- name: Clean generated Toolkit build
|
||||
if: always()
|
||||
run: python3 ci/cleanup-generated.py
|
||||
|
||||
@@ -22,8 +22,8 @@ use alkane_flash::preflight::{preflight, PreflightOptions};
|
||||
use alkane_flash::stock;
|
||||
use alkane_flash::stock::{InPlaceOptions, InPlaceOutcome, RestoreImages};
|
||||
use alkane_flash::stock_firmware;
|
||||
use alkane_flash::zynq_nand;
|
||||
use alkane_flash::transport::{Remote, RootMethod, SshOptions, SshTransport};
|
||||
use alkane_flash::zynq_nand;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -1042,7 +1042,10 @@ fn latest_backup(dir: &Path) -> Option<PathBuf> {
|
||||
/// of these; `compat` lists them so an operator knows what is supported.
|
||||
const SUPPORTED: &[(&str, &str)] = &[
|
||||
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
|
||||
("a113d", "Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)"),
|
||||
(
|
||||
"a113d",
|
||||
"Antminer BHB42XXX / S19k Pro (Amlogic A113D/AXG control board)",
|
||||
),
|
||||
];
|
||||
|
||||
fn is_supported(board: &str) -> bool {
|
||||
@@ -1128,7 +1131,9 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
|
||||
None => {
|
||||
if opts.flag("dry-run") {
|
||||
println!("DRY RUN: would restore {host} to stock by flipping the A113D boot flag");
|
||||
println!("(no stock firmware needed; the untouched stock boot partition is booted).");
|
||||
println!(
|
||||
"(no stock firmware needed; the untouched stock boot partition is booted)."
|
||||
);
|
||||
println!("Re-run with --confirm FLASH.");
|
||||
return Ok(());
|
||||
}
|
||||
@@ -1138,7 +1143,9 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
|
||||
println!("restoring {host} to genuine stock (A113D flag flip, network-only)...");
|
||||
match stock::restore_aml_flag(&host, password.as_deref()) {
|
||||
Ok(()) => {
|
||||
println!("restore reported success (boot flag cleared; stock boots via storeboot).");
|
||||
println!(
|
||||
"restore reported success (boot flag cleared; stock boots via storeboot)."
|
||||
);
|
||||
println!("verify independently: the board should present genuine stock");
|
||||
println!("(cgminer API on :4028, lighttpd 401 on :80, dropbear 2018.x).");
|
||||
return Ok(());
|
||||
@@ -1186,9 +1193,7 @@ fn run_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>>
|
||||
fn run_root_run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let opts = parse_args(args, ssh_values(), &[])?;
|
||||
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||
let cmd = opts
|
||||
.positionals
|
||||
.join(" ");
|
||||
let cmd = opts.positionals.join(" ");
|
||||
if cmd.trim().is_empty() {
|
||||
return Err("usage: alkane-cli afw root-run --host <ip> <command...>".into());
|
||||
}
|
||||
@@ -1203,7 +1208,11 @@ fn run_root_run(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// backup, write the boot slots and reboot. Drives the DSH root-on-stock
|
||||
/// primitive; board must be on stock (credential root/root).
|
||||
fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let opts = parse_args(args, &[ssh_values(), &["confirm"]].concat(), &["allow-unsigned"])?;
|
||||
let opts = parse_args(
|
||||
args,
|
||||
&[ssh_values(), &["confirm"]].concat(),
|
||||
&["allow-unsigned"],
|
||||
)?;
|
||||
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||
let afw_path = opts
|
||||
.positionals
|
||||
@@ -1211,18 +1220,33 @@ fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
.ok_or("usage: alkane-cli afw nand-install <afw> --host <ip> --confirm FLASH")?;
|
||||
let verified = load_afw(afw_path, &opts)?;
|
||||
if !zynq::owns_board(&verified.manifest.board) {
|
||||
return Err(format!("nand-install is zynq-7010 only, not {}", verified.manifest.board).into());
|
||||
return Err(format!(
|
||||
"nand-install is zynq-7010 only, not {}",
|
||||
verified.manifest.board
|
||||
)
|
||||
.into());
|
||||
}
|
||||
if opts.value("confirm") != Some("FLASH") {
|
||||
return Err("refusing to install without --confirm FLASH".into());
|
||||
}
|
||||
let kernel = verified.image("kernel").ok_or("afw missing kernel image")?.1;
|
||||
let kernel = verified
|
||||
.image("kernel")
|
||||
.ok_or("afw missing kernel image")?
|
||||
.1;
|
||||
let dtb = verified.image("dtb").ok_or("afw missing dtb image")?.1;
|
||||
let rootfs = verified.image("rootfs").ok_or("afw missing rootfs image")?.1;
|
||||
let rootfs = verified
|
||||
.image("rootfs")
|
||||
.ok_or("afw missing rootfs image")?
|
||||
.1;
|
||||
let password = read_board_password(&opts)?;
|
||||
println!("installing {} onto stock board {host} (readable NAND path)...", verified.manifest.board);
|
||||
println!(
|
||||
"installing {} onto stock board {host} (readable NAND path)...",
|
||||
verified.manifest.board
|
||||
);
|
||||
zynq_nand::install_from_stock(&host, kernel, dtb, rootfs, password.as_deref())?;
|
||||
println!("install reported success (on-board stock backup carved; boot slots written; rebooting).");
|
||||
println!(
|
||||
"install reported success (on-board stock backup carved; boot slots written; rebooting)."
|
||||
);
|
||||
print!("{}", zynq_verify_hint(&host));
|
||||
Ok(())
|
||||
}
|
||||
@@ -1231,9 +1255,15 @@ fn run_nand_install(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// back to the boot slots over SSH (board on alkane). Needs the alkane image
|
||||
/// that exposes the boot partitions.
|
||||
fn run_nand_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let opts = parse_args(args, &[ssh_values(), &["confirm", "stock-firmware"]].concat(), &["dry-run"])?;
|
||||
let opts = parse_args(
|
||||
args,
|
||||
&[ssh_values(), &["confirm", "stock-firmware"]].concat(),
|
||||
&["dry-run"],
|
||||
)?;
|
||||
let host = opts.value("host").ok_or("--host is required")?.to_owned();
|
||||
let firmware = opts.value("stock-firmware").ok_or("--stock-firmware <file> is required")?;
|
||||
let firmware = opts
|
||||
.value("stock-firmware")
|
||||
.ok_or("--stock-firmware <file> is required")?;
|
||||
let fw = stock_firmware::parse(Path::new(firmware))?;
|
||||
println!("stock firmware: {}", fw.summary());
|
||||
if opts.value("confirm") != Some("FLASH") {
|
||||
@@ -1241,8 +1271,16 @@ fn run_nand_restore_stock(args: &[String]) -> Result<(), Box<dyn std::error::Err
|
||||
}
|
||||
let password = read_board_password(&opts)?;
|
||||
println!("restoring {host} to genuine stock (readable NAND path)...");
|
||||
zynq_nand::restore_to_stock(&host, &fw.kernel, &fw.rootfs, fw.dtb.as_deref(), password.as_deref())?;
|
||||
println!("restore-to-stock reported success (stock kernel/dtb/rootfs written, BOOT.bin preserved).");
|
||||
zynq_nand::restore_to_stock(
|
||||
&host,
|
||||
&fw.kernel,
|
||||
&fw.rootfs,
|
||||
fw.dtb.as_deref(),
|
||||
password.as_deref(),
|
||||
)?;
|
||||
println!(
|
||||
"restore-to-stock reported success (stock kernel/dtb/rootfs written, BOOT.bin preserved)."
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1344,7 +1382,9 @@ fn run_restore_onboard(args: &[String]) -> Result<(), Box<dyn std::error::Error>
|
||||
password.as_deref(),
|
||||
std::time::Duration::from_secs(300),
|
||||
)?;
|
||||
println!("restore-from-onboard reported success. Verify independently the board answers as stock.");
|
||||
println!(
|
||||
"restore-from-onboard reported success. Verify independently the board answers as stock."
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -53,8 +53,7 @@ const FLAG_MAGIC: [u8; 4] = *b"ALAN";
|
||||
const KRNADDR: &str = "0x1200000";
|
||||
const FDTADDR: &str = "0x8000000";
|
||||
const RDADDR: &str = "0x8100000";
|
||||
const ALK_BOOTARGS: &str =
|
||||
"console=ttyAML0,115200 earlycon=meson,0xff803000 no_console_suspend";
|
||||
const ALK_BOOTARGS: &str = "console=ttyAML0,115200 earlycon=meson,0xff803000 no_console_suspend";
|
||||
|
||||
/// The on-board basenames inside the nvdata UBI volume's `alkane/` directory.
|
||||
const ALKANE_DIR: &str = "alkane";
|
||||
@@ -110,8 +109,8 @@ impl AlkaneShell {
|
||||
root_method: crate::transport::RootMethod::Auto,
|
||||
update_daemon_port: None,
|
||||
};
|
||||
let transport = SshTransport::connect(options, true)
|
||||
.map_err(|e| StockError::Network(e.to_string()))?;
|
||||
let transport =
|
||||
SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?;
|
||||
Ok(AlkaneShell {
|
||||
transport,
|
||||
_secret: secret,
|
||||
@@ -220,7 +219,7 @@ fn b64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
|
||||
fn b64_encode(data: &[u8]) -> String {
|
||||
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::with_capacity((data.len() + 2) / 3 * 4);
|
||||
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for chunk in data.chunks(3) {
|
||||
let b = [
|
||||
chunk[0],
|
||||
@@ -607,7 +606,10 @@ mod tests {
|
||||
#[test]
|
||||
fn env_roundtrips_with_crc() {
|
||||
let vars = vec![
|
||||
("bootcmd".to_owned(), "run checkalk; run storeboot".to_owned()),
|
||||
(
|
||||
"bootcmd".to_owned(),
|
||||
"run checkalk; run storeboot".to_owned(),
|
||||
),
|
||||
("bootdelay".to_owned(), "1".to_owned()),
|
||||
("checkalk".to_owned(), checkalk_value()),
|
||||
];
|
||||
@@ -616,8 +618,10 @@ mod tests {
|
||||
let stored = u32::from_le_bytes([blob[0], blob[1], blob[2], blob[3]]);
|
||||
assert_eq!(crc32(&blob[4..]), stored);
|
||||
let parsed = parse_env(&blob);
|
||||
assert_eq!(parsed.iter().find(|(k, _)| k == "bootcmd").unwrap().1,
|
||||
"run checkalk; run storeboot");
|
||||
assert_eq!(
|
||||
parsed.iter().find(|(k, _)| k == "bootcmd").unwrap().1,
|
||||
"run checkalk; run storeboot"
|
||||
);
|
||||
assert!(parsed.iter().any(|(k, _)| k == "checkalk"));
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,8 @@ pub mod zynq_nand;
|
||||
clippy::too_many_arguments,
|
||||
clippy::manual_repeat_n,
|
||||
clippy::manual_is_multiple_of,
|
||||
clippy::unnecessary_map_or
|
||||
clippy::unnecessary_map_or,
|
||||
clippy::question_mark
|
||||
)]
|
||||
mod stock_method;
|
||||
pub mod transport;
|
||||
|
||||
@@ -34,7 +34,6 @@ use crate::md5::md5_hex;
|
||||
use crate::stock::StockError;
|
||||
use crate::transport::{Remote, SshOptions, SshTransport};
|
||||
use crate::uimage::{self, Kind};
|
||||
use std::io::Write as _;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
@@ -131,6 +130,7 @@ impl Drop for TempFile {
|
||||
|
||||
#[cfg(unix)]
|
||||
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
|
||||
use std::io::Write as _;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let mut f = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
@@ -142,6 +142,11 @@ fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
|
||||
f.flush()
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
|
||||
std::fs::write(path, contents)
|
||||
}
|
||||
|
||||
impl AlkaneShell {
|
||||
fn connect(host: &str, password: Option<&str>) -> Result<Self, StockError> {
|
||||
let secret = TempFile::with(password.unwrap_or("alkane").as_bytes(), "pw")?;
|
||||
@@ -157,8 +162,8 @@ impl AlkaneShell {
|
||||
root_method: crate::transport::RootMethod::Auto,
|
||||
update_daemon_port: None,
|
||||
};
|
||||
let transport = SshTransport::connect(options, true)
|
||||
.map_err(|e| StockError::Network(e.to_string()))?;
|
||||
let transport =
|
||||
SshTransport::connect(options, true).map_err(|e| StockError::Network(e.to_string()))?;
|
||||
Ok(AlkaneShell {
|
||||
transport,
|
||||
_secret: secret,
|
||||
@@ -225,11 +230,7 @@ fn read_mtd_table(sh: &mut dyn Shell) -> Result<Vec<Mtd>, StockError> {
|
||||
.and_then(|h| u64::from_str_radix(h, 16).ok())
|
||||
.ok_or_else(|| StockError::Method(format!("bad /proc/mtd line: {line}")))?;
|
||||
let _erase = it.next();
|
||||
let name = line
|
||||
.split('"')
|
||||
.nth(1)
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
let name = line.split('"').nth(1).unwrap_or("").to_owned();
|
||||
let base = match sysfs_offset(sh, dev) {
|
||||
Some(off) => off,
|
||||
None => cursor,
|
||||
@@ -257,11 +258,7 @@ fn sysfs_offset(sh: &mut dyn Shell, dev: &str) -> Option<u64> {
|
||||
|
||||
/// Find the partition that contains `abs` and holding at least `len` bytes from
|
||||
/// there; return (device, relative offset).
|
||||
fn locate<'a>(
|
||||
table: &'a [Mtd],
|
||||
abs: u64,
|
||||
len: u64,
|
||||
) -> Result<(&'a str, u64), StockError> {
|
||||
fn locate(table: &[Mtd], abs: u64, len: u64) -> Result<(&str, u64), StockError> {
|
||||
for m in table {
|
||||
if abs >= m.base && abs < m.base + m.size {
|
||||
let rel = abs - m.base;
|
||||
@@ -308,7 +305,7 @@ fn write_abs(
|
||||
"refusing to write {label} at 0x{abs:x}: inside preserved BOOT.bin"
|
||||
)));
|
||||
}
|
||||
if abs % ERASE != 0 {
|
||||
if !abs.is_multiple_of(ERASE) {
|
||||
return Err(StockError::Method(format!(
|
||||
"{label} offset 0x{abs:x} is not erase-block aligned"
|
||||
)));
|
||||
@@ -335,7 +332,9 @@ fn write_abs(
|
||||
if o.contains("WROTE") {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(StockError::Method(format!("{label}: erase/write failed: {o}")))
|
||||
Err(StockError::Method(format!(
|
||||
"{label}: erase/write failed: {o}"
|
||||
)))
|
||||
}
|
||||
})?;
|
||||
let readlen = round_up(data.len() as u64, PAGE);
|
||||
@@ -488,7 +487,7 @@ fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, Sto
|
||||
let dtb_len = read_header_u32_be(sh, table, OFF_DTB, 4)? as u64;
|
||||
let rootfs_len = 64 + read_header_u32_be(sh, table, OFF_ROOTFS, 12)? as u64;
|
||||
// Sanity: headers must look like a uImage/fdt, sizes within slots.
|
||||
if kernel_len < 64 || kernel_len > SLOT_KERNEL || rootfs_len < 64 || rootfs_len > SLOT_ROOTFS {
|
||||
if !(64..=SLOT_KERNEL).contains(&kernel_len) || !(64..=SLOT_ROOTFS).contains(&rootfs_len) {
|
||||
return Err(StockError::Method(format!(
|
||||
"stock image sizes implausible (kernel {kernel_len}, rootfs {rootfs_len}); \
|
||||
refusing to back up"
|
||||
@@ -513,7 +512,13 @@ fn carve_backup(sh: &mut dyn Shell, table: &[Mtd]) -> Result<BackupManifest, Sto
|
||||
rootfs_abs: r_dst,
|
||||
rootfs_len,
|
||||
};
|
||||
write_abs(sh, table, BK_MANIFEST, &manifest.encode(), "stock-backup-manifest")?;
|
||||
write_abs(
|
||||
sh,
|
||||
table,
|
||||
BK_MANIFEST,
|
||||
&manifest.encode(),
|
||||
"stock-backup-manifest",
|
||||
)?;
|
||||
Ok(manifest)
|
||||
}
|
||||
|
||||
@@ -569,11 +574,7 @@ struct BootImages {
|
||||
rootfs_uimage: Vec<u8>,
|
||||
}
|
||||
|
||||
fn write_boot_slots(
|
||||
sh: &mut dyn Shell,
|
||||
table: &[Mtd],
|
||||
img: &BootImages,
|
||||
) -> Result<(), StockError> {
|
||||
fn write_boot_slots(sh: &mut dyn Shell, table: &[Mtd], img: &BootImages) -> Result<(), StockError> {
|
||||
// rootfs, dtb, kernel order: an interrupted run never leaves a new rootfs
|
||||
// under an old kernel.
|
||||
if img.rootfs_uimage.len() as u64 > SLOT_ROOTFS {
|
||||
@@ -623,7 +624,9 @@ pub fn install_from_stock(
|
||||
password: password.map(str::to_owned),
|
||||
};
|
||||
if first_token(&sh.exec("id -u")?) != "0" {
|
||||
return Err(StockError::Auth("did not obtain root on the stock board".into()));
|
||||
return Err(StockError::Auth(
|
||||
"did not obtain root on the stock board".into(),
|
||||
));
|
||||
}
|
||||
let table = read_mtd_table(&mut sh)?;
|
||||
// Carve the genuine-stock backup from the live stock NAND before any write.
|
||||
@@ -674,7 +677,14 @@ pub fn restore_to_stock(
|
||||
"no stock dtb supplied and no on-board backup to take one from".into(),
|
||||
)
|
||||
})?;
|
||||
copy_abs(&mut sh, &table, manifest.dtb_abs, OFF_DTB, manifest.dtb_len, "dtb")?;
|
||||
copy_abs(
|
||||
&mut sh,
|
||||
&table,
|
||||
manifest.dtb_abs,
|
||||
OFF_DTB,
|
||||
manifest.dtb_len,
|
||||
"dtb",
|
||||
)?;
|
||||
}
|
||||
}
|
||||
write_abs(&mut sh, &table, OFF_KERNEL, kernel_uimage, "kernel")?;
|
||||
@@ -703,14 +713,34 @@ pub fn restore_from_onboard(host: &str, password: Option<&str>) -> Result<(), St
|
||||
let manifest = read_backup_manifest(&mut sh, &table)?
|
||||
.ok_or_else(|| StockError::Method("no complete on-board stock backup".into()))?;
|
||||
// Copy within NAND: backup region -> boot slots.
|
||||
copy_abs(&mut sh, &table, manifest.rootfs_abs, OFF_ROOTFS, manifest.rootfs_len, "rootfs")?;
|
||||
copy_abs(&mut sh, &table, manifest.dtb_abs, OFF_DTB, manifest.dtb_len, "dtb")?;
|
||||
copy_abs(&mut sh, &table, manifest.kernel_abs, OFF_KERNEL, manifest.kernel_len, "kernel")?;
|
||||
copy_abs(
|
||||
&mut sh,
|
||||
&table,
|
||||
manifest.rootfs_abs,
|
||||
OFF_ROOTFS,
|
||||
manifest.rootfs_len,
|
||||
"rootfs",
|
||||
)?;
|
||||
copy_abs(
|
||||
&mut sh,
|
||||
&table,
|
||||
manifest.dtb_abs,
|
||||
OFF_DTB,
|
||||
manifest.dtb_len,
|
||||
"dtb",
|
||||
)?;
|
||||
copy_abs(
|
||||
&mut sh,
|
||||
&table,
|
||||
manifest.kernel_abs,
|
||||
OFF_KERNEL,
|
||||
manifest.kernel_len,
|
||||
"kernel",
|
||||
)?;
|
||||
reboot(&mut sh);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -751,8 +781,18 @@ mod tests {
|
||||
#[test]
|
||||
fn locate_maps_absolute_to_partition() {
|
||||
let table = vec![
|
||||
Mtd { dev: "mtd0".into(), base: 0x0, size: 0x2800000, name: "x".into() },
|
||||
Mtd { dev: "mtd1".into(), base: 0x2800000, size: 0x2000000, name: "y".into() },
|
||||
Mtd {
|
||||
dev: "mtd0".into(),
|
||||
base: 0x0,
|
||||
size: 0x2800000,
|
||||
name: "x".into(),
|
||||
},
|
||||
Mtd {
|
||||
dev: "mtd1".into(),
|
||||
base: 0x2800000,
|
||||
size: 0x2000000,
|
||||
name: "y".into(),
|
||||
},
|
||||
];
|
||||
assert_eq!(locate(&table, 0x2000000, 100).unwrap(), ("mtd0", 0x2000000));
|
||||
assert_eq!(locate(&table, 0x2800000, 100).unwrap(), ("mtd1", 0));
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
//! Headless bench automation (`ALKANE_BENCH_SEQUENCE`): drive the GUI's real
|
||||
//! install/restore operation layer (`stock_ops`) through the A113D network-only
|
||||
//! install <-> flag-restore cycle, with no window. This exercises the GUI
|
||||
//! operator flow end-to-end against real hardware, for bench proofs, without the
|
||||
//! wx event loop (the worker functions stream progress over a channel, exactly
|
||||
//! as the UI drains them).
|
||||
//!
|
||||
//! Spec: `ALKANE_BENCH_SEQUENCE="<host> <local.afw> [iterations]"`.
|
||||
//! The alkane root credential is read from the saved SSH credentials file.
|
||||
//!
|
||||
//! On the A113D, "restore to stock" is the one-byte flag flip (the install
|
||||
//! overwrites no stock partition), so the cycle is: install (stock -> alkane) ->
|
||||
//! verify alkane -> restore (flag flip -> stock) -> verify stock.
|
||||
|
||||
use std::io::Read;
|
||||
use std::net::TcpStream;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::credentials;
|
||||
use crate::stock_ops::{self, AfwSource, StockHandle, StockMsg};
|
||||
|
||||
/// Drain a `StockHandle` to completion, printing progress; returns true iff
|
||||
/// every board reported ok and at least one `Result` arrived.
|
||||
fn drive(label: &str, handle: StockHandle) -> bool {
|
||||
let mut ok = true;
|
||||
let mut saw = false;
|
||||
loop {
|
||||
match handle.rx.recv() {
|
||||
Ok(StockMsg::Started) => println!(" [{label}] started"),
|
||||
Ok(StockMsg::Progress(s)) => println!(" [{label}] {s}"),
|
||||
Ok(StockMsg::Result { ip, ok: r, detail }) => {
|
||||
saw = true;
|
||||
ok = ok && r;
|
||||
println!(
|
||||
" [{label}] {ip}: {} - {detail}",
|
||||
if r { "OK" } else { "FAIL" }
|
||||
);
|
||||
}
|
||||
Ok(StockMsg::Done) => break,
|
||||
Err(_) => {
|
||||
println!(" [{label}] channel closed early");
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
ok && saw
|
||||
}
|
||||
|
||||
/// Read the SSH identification banner (no auth), e.g. `SSH-2.0-dropbear_2026.93`.
|
||||
fn ssh_banner(host: &str) -> Option<String> {
|
||||
let addr: std::net::SocketAddr = format!("{host}:22").parse().ok()?;
|
||||
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(5)).ok()?;
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).ok()?;
|
||||
let mut buf = [0u8; 256];
|
||||
let n = stream.read(&mut buf).ok()?;
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
String::from_utf8_lossy(&buf[..n])
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// HTTP server header probe (stock serves lighttpd / an antMiner realm).
|
||||
fn http_is_stock(host: &str) -> Option<bool> {
|
||||
let out = Command::new("curl")
|
||||
.args([
|
||||
"-sS",
|
||||
"-m",
|
||||
"6",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-D",
|
||||
"-",
|
||||
&format!("http://{host}/"),
|
||||
])
|
||||
.output()
|
||||
.ok()?;
|
||||
let h = String::from_utf8_lossy(&out.stdout).to_lowercase();
|
||||
if h.is_empty() {
|
||||
None
|
||||
} else if h.contains("lighttpd") || h.contains("antminer configuration") {
|
||||
Some(true)
|
||||
} else {
|
||||
Some(false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify the board: `Some(true)` = looks like genuine stock, `Some(false)` =
|
||||
/// looks like alkane, `None` = no decisive answer (e.g. mid-reboot).
|
||||
///
|
||||
/// Primary signal is the SSH banner: stock A113D is `dropbear_2018.76`; alkane
|
||||
/// ships a much newer dropbear. HTTP (lighttpd) is a stock fallback.
|
||||
fn classify(host: &str) -> (String, Option<bool>) {
|
||||
let banner = ssh_banner(host);
|
||||
if let Some(b) = &banner {
|
||||
let lb = b.to_lowercase();
|
||||
if lb.contains("dropbear_2018") || lb.contains("dropbear_2019") {
|
||||
return (format!("ssh \"{b}\" -> stock"), Some(true));
|
||||
}
|
||||
if lb.contains("dropbear") || lb.contains("openssh") {
|
||||
return (format!("ssh \"{b}\" -> alkane"), Some(false));
|
||||
}
|
||||
}
|
||||
match http_is_stock(host) {
|
||||
Some(true) => ("http lighttpd/antMiner -> stock".to_string(), Some(true)),
|
||||
Some(false) => ("http non-stock -> alkane".to_string(), Some(false)),
|
||||
None => (
|
||||
banner
|
||||
.map(|b| format!("ssh \"{b}\" (unclassified), no http"))
|
||||
.unwrap_or_else(|| "no ssh, no http (mid-reboot?)".to_string()),
|
||||
None,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The MAC (lladdr) the kernel has cached for `host` (pings first to populate).
|
||||
fn mac_of(host: &str) -> Option<String> {
|
||||
let _ = Command::new("ping")
|
||||
.args(["-c", "1", "-W", "1", host])
|
||||
.output();
|
||||
let out = Command::new("ip")
|
||||
.args(["neigh", "show", host])
|
||||
.output()
|
||||
.ok()?;
|
||||
let s = String::from_utf8_lossy(&out.stdout);
|
||||
let mut it = s.split_whitespace();
|
||||
while let Some(t) = it.next() {
|
||||
if t == "lladdr" {
|
||||
return it.next().map(|m| m.to_lowercase());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Populate the neighbour table by parallel-pinging the /24 of `sample` (a bench
|
||||
/// board can take a different DHCP lease across a reboot, so we must re-find it).
|
||||
fn sweep_subnet(sample: &str) {
|
||||
let base = match sample.rsplit_once('.') {
|
||||
Some((net, _)) => net.to_string(),
|
||||
None => return,
|
||||
};
|
||||
let mut kids = Vec::new();
|
||||
for h in 2..=254 {
|
||||
if let Ok(c) = Command::new("ping")
|
||||
.args(["-c", "1", "-W", "1", &format!("{base}.{h}")])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
{
|
||||
kids.push(c);
|
||||
}
|
||||
}
|
||||
for mut c in kids {
|
||||
let _ = c.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// Current IPv4 for `mac` from the neighbour table, if present.
|
||||
fn ip_for_mac(mac: &str) -> Option<String> {
|
||||
let out = Command::new("ip").args(["neigh"]).output().ok()?;
|
||||
let s = String::from_utf8_lossy(&out.stdout);
|
||||
let mac = mac.to_lowercase();
|
||||
for line in s.lines() {
|
||||
if line.to_lowercase().contains(&mac) {
|
||||
if let Some(ip) = line.split_whitespace().next() {
|
||||
if ip.contains('.') {
|
||||
return Some(ip.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Poll until the board (located by MAC, so a changed DHCP lease is followed)
|
||||
/// reaches the wanted stock-ness, or `timeout` elapses. Returns the board's
|
||||
/// current IP, a description, and whether the target state was reached.
|
||||
fn wait_for(
|
||||
mac: Option<&str>,
|
||||
fallback: &str,
|
||||
want_stock: bool,
|
||||
timeout: Duration,
|
||||
) -> (String, String, bool) {
|
||||
let deadline = Instant::now() + timeout;
|
||||
let mut ip = fallback.to_string();
|
||||
let mut swept = Instant::now() - Duration::from_secs(60);
|
||||
loop {
|
||||
// Re-locate by MAC; sweep the subnet at most every ~25s to catch a new lease.
|
||||
if let Some(m) = mac {
|
||||
if ip_for_mac(m).is_none() && swept.elapsed() >= Duration::from_secs(25) {
|
||||
sweep_subnet(fallback);
|
||||
swept = Instant::now();
|
||||
}
|
||||
if let Some(found) = ip_for_mac(m) {
|
||||
ip = found;
|
||||
}
|
||||
}
|
||||
let (desc, is_stock) = classify(&ip);
|
||||
let line = format!("[{ip}] {desc}");
|
||||
if is_stock == Some(want_stock) {
|
||||
return (ip, line, true);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return (ip, line, false);
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(spec: &str) -> i32 {
|
||||
let mut it = spec.split_whitespace();
|
||||
let host = match it.next() {
|
||||
Some(h) => h.to_string(),
|
||||
None => {
|
||||
eprintln!("ALKANE_BENCH_SEQUENCE=\"<host> <local.afw> [iterations]\"");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let afw = match it.next() {
|
||||
Some(a) => PathBuf::from(a),
|
||||
None => {
|
||||
eprintln!("missing local .afw path");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
let iterations: u32 = it.next().and_then(|s| s.parse().ok()).unwrap_or(1);
|
||||
let board = "a113d".to_string();
|
||||
// Install reaches STOCK via the compiled-in from-stock method; pass the saved
|
||||
// board SSH credential through to it.
|
||||
let stock_password = credentials::load_ssh_credentials().map(|(_, p)| p);
|
||||
// The flag-restore reaches the running ALKANE board over SSH as `root` - a
|
||||
// DIFFERENT credential from the stock login. Alkane bench images bake
|
||||
// root/alkane; allow an override via ALKANE_ROOT_PASSWORD.
|
||||
let alkane_password = std::env::var("ALKANE_ROOT_PASSWORD")
|
||||
.ok()
|
||||
.or_else(|| Some("alkane".to_string()));
|
||||
|
||||
println!("== A113D headless GUI bench sequence (network-only install <-> flag-restore) ==");
|
||||
println!(
|
||||
"host={host} afw={} board={board} iterations={iterations} stock_cred={} alkane_cred={}",
|
||||
afw.display(),
|
||||
if stock_password.is_some() { "loaded" } else { "none" },
|
||||
if alkane_password.is_some() { "set" } else { "none" }
|
||||
);
|
||||
if !afw.exists() {
|
||||
eprintln!("afw not found: {}", afw.display());
|
||||
return 2;
|
||||
}
|
||||
|
||||
// Resolve the board's MAC now (on stock) so we can re-find it after each
|
||||
// reboot even if its DHCP lease changes under alkane.
|
||||
let mac = mac_of(&host);
|
||||
println!(
|
||||
"board MAC: {}",
|
||||
mac.as_deref()
|
||||
.unwrap_or("unknown (will use the fixed host)")
|
||||
);
|
||||
|
||||
let boot_timeout = Duration::from_secs(300);
|
||||
let mut all_ok = true;
|
||||
|
||||
for i in 1..=iterations {
|
||||
println!("\n-- iteration {i}/{iterations} --");
|
||||
|
||||
// 1. install (stock -> alkane) through the GUI operation layer
|
||||
println!("[1/4] install: stock -> alkane");
|
||||
let h = stock_ops::start_install(
|
||||
vec![host.clone()],
|
||||
board.clone(),
|
||||
AfwSource::Local(afw.clone()),
|
||||
true, // allow unsigned (bench image)
|
||||
stock_password.clone(),
|
||||
false, // not an in-place update
|
||||
);
|
||||
if !drive("install", h) {
|
||||
all_ok = false;
|
||||
println!("[1/4] install FAILED; aborting");
|
||||
break;
|
||||
}
|
||||
|
||||
// 2. verify alkane is live (board reboots into alkane)
|
||||
println!(
|
||||
"[2/4] verify alkane (awaiting reboot, up to {}s)...",
|
||||
boot_timeout.as_secs()
|
||||
);
|
||||
let (alkane_ip, desc, ok) = wait_for(mac.as_deref(), &host, false, boot_timeout);
|
||||
println!(
|
||||
" {desc} => {}",
|
||||
if ok { "ALKANE" } else { "NOT ALKANE (fail)" }
|
||||
);
|
||||
all_ok = all_ok && ok;
|
||||
|
||||
// 3. restore (alkane -> stock) flag-flip at the board's CURRENT address
|
||||
println!("[3/4] restore: alkane -> stock (flag flip) at {alkane_ip}");
|
||||
let h = stock_ops::start_restore_flag(vec![alkane_ip.clone()], alkane_password.clone());
|
||||
if !drive("restore", h) {
|
||||
all_ok = false;
|
||||
println!("[3/4] restore FAILED");
|
||||
}
|
||||
|
||||
// 4. verify stock is back
|
||||
println!(
|
||||
"[4/4] verify stock (awaiting reboot, up to {}s)...",
|
||||
boot_timeout.as_secs()
|
||||
);
|
||||
let (_stock_ip, desc, ok) = wait_for(mac.as_deref(), &host, true, boot_timeout);
|
||||
println!(
|
||||
" {desc} => {}",
|
||||
if ok { "STOCK" } else { "NOT STOCK (fail)" }
|
||||
);
|
||||
all_ok = all_ok && ok;
|
||||
}
|
||||
|
||||
println!(
|
||||
"\n== BENCH RESULT: {} ==",
|
||||
if all_ok { "PASS" } else { "FAIL" }
|
||||
);
|
||||
if all_ok {
|
||||
0
|
||||
} else {
|
||||
1
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
mod access_probe;
|
||||
mod alkane_detect;
|
||||
mod askpass;
|
||||
mod bench_sequence;
|
||||
mod bug_report;
|
||||
mod credentials;
|
||||
mod export;
|
||||
@@ -41,6 +42,13 @@ fn main() {
|
||||
std::process::exit(run_selftest());
|
||||
}
|
||||
|
||||
// Headless bench automation: drive the real install/restore operation layer
|
||||
// (stock_ops) through the A113D network-only install <-> flag-restore cycle
|
||||
// against real hardware, with no window. See bench_sequence.rs.
|
||||
if let Some(spec) = std::env::var_os("ALKANE_BENCH_SEQUENCE") {
|
||||
std::process::exit(bench_sequence::run(&spec.to_string_lossy()));
|
||||
}
|
||||
|
||||
// Headless access-probe check: `ALKANE_ACCESS_PROBE="<ip> <make>"` prints the
|
||||
// lock state the real access probe computes (no GUI, no wx), so the WhatsMiner
|
||||
// :4028 token check and the Antminer digest check can be verified directly.
|
||||
@@ -123,9 +131,14 @@ fn run_selftest() -> i32 {
|
||||
|
||||
/// True when the process runs one of the headless check modes instead of the GUI.
|
||||
fn headless_mode() -> bool {
|
||||
["ALKANE_SELFTEST", "ALKANE_ACCESS_PROBE", "ALKANE_LOG_SCAN"]
|
||||
.iter()
|
||||
.any(|v| std::env::var_os(v).is_some())
|
||||
[
|
||||
"ALKANE_SELFTEST",
|
||||
"ALKANE_ACCESS_PROBE",
|
||||
"ALKANE_LOG_SCAN",
|
||||
"ALKANE_BENCH_SEQUENCE",
|
||||
]
|
||||
.iter()
|
||||
.any(|v| std::env::var_os(v).is_some())
|
||||
}
|
||||
|
||||
/// A Windows GUI-subsystem process has no console, so output from the headless
|
||||
|
||||
@@ -24,8 +24,13 @@ use crate::scan::fake_scan_enabled;
|
||||
|
||||
/// Control boards alkane-os can be installed onto from stock (mirrors the CLI's
|
||||
/// `SUPPORTED`). Only these are offered as install targets.
|
||||
pub const SUPPORTED_BOARDS: &[(&str, &str)] =
|
||||
&[("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)")];
|
||||
pub const SUPPORTED_BOARDS: &[(&str, &str)] = &[
|
||||
("zynq-7010", "Antminer S17 (Xilinx Zynq-7010 control board)"),
|
||||
(
|
||||
"a113d",
|
||||
"Antminer S19j Pro (Amlogic A113D/AXG control board)",
|
||||
),
|
||||
];
|
||||
|
||||
/// The default install board when the user has not chosen another.
|
||||
pub const DEFAULT_BOARD: &str = "zynq-7010";
|
||||
@@ -408,3 +413,65 @@ pub fn start_restore_onboard(ips: Vec<String>, password: Option<String>) -> Stoc
|
||||
}
|
||||
StockHandle { rx, cancel }
|
||||
}
|
||||
|
||||
/// Restore the given alkane A113D boards to genuine Bitmain stock, over the
|
||||
/// network, by clearing the one-byte boot flag in-band from the running alkane
|
||||
/// OS. The A113D install overwrites no stock partition, so this flag flip is the
|
||||
/// complete restore: clear `ALAN`, reboot, and stock boots via `storeboot` from
|
||||
/// the untouched `boot` MTD. No vendor firmware file or on-board backup needed.
|
||||
/// `password`, if set, is the board's alkane root credential.
|
||||
pub fn start_restore_flag(ips: Vec<String>, password: Option<String>) -> StockHandle {
|
||||
let (tx, rx) = channel();
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
|
||||
if fake_scan_enabled() {
|
||||
let _ = tx.send(StockMsg::Started);
|
||||
for ip in ips {
|
||||
let _ = tx.send(StockMsg::Result {
|
||||
ip,
|
||||
ok: true,
|
||||
detail: "restored to stock (flag flip, demo)".into(),
|
||||
});
|
||||
}
|
||||
let _ = tx.send(StockMsg::Done);
|
||||
return StockHandle { rx, cancel };
|
||||
}
|
||||
|
||||
let tc = cancel.clone();
|
||||
let err_tx = tx.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("restore-flag".into())
|
||||
.spawn(move || {
|
||||
let _ = tx.send(StockMsg::Started);
|
||||
for ip in ips {
|
||||
if tc.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
let _ = tx.send(StockMsg::Progress(format!(
|
||||
"restoring {ip} to stock (clearing the alkane boot flag)..."
|
||||
)));
|
||||
let (ok, detail) = match stock::restore_aml_flag(&ip, password.as_deref()) {
|
||||
Ok(()) => (
|
||||
true,
|
||||
"restored to stock (flag cleared, rebooting; verify over the network)"
|
||||
.to_string(),
|
||||
),
|
||||
Err(e) => (false, format!("restore failed: {e}")),
|
||||
};
|
||||
if tx.send(StockMsg::Result { ip, ok, detail }).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let _ = tx.send(StockMsg::Done);
|
||||
});
|
||||
|
||||
if spawned.is_err() {
|
||||
let _ = err_tx.send(StockMsg::Result {
|
||||
ip: String::new(),
|
||||
ok: false,
|
||||
detail: "could not start the restore worker thread".into(),
|
||||
});
|
||||
let _ = err_tx.send(StockMsg::Done);
|
||||
}
|
||||
StockHandle { rx, cancel }
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import json
|
||||
import pathlib
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
@@ -16,6 +17,12 @@ import relay # noqa: E402
|
||||
|
||||
TOKEN = "test-token-123"
|
||||
|
||||
# The repository's labels, as the real Gitea /labels endpoint would return them.
|
||||
# The mock serves these, and setUp seeds the relay client's label cache from the
|
||||
# same list so label resolution is deterministic (see RelayTests.setUp).
|
||||
REPO_LABELS = [{"name": "bug", "id": 1}, {"name": "ui", "id": 2},
|
||||
{"name": "feature", "id": 3}, {"name": "from-app", "id": 9}]
|
||||
|
||||
|
||||
class FakeGitea:
|
||||
"""Records issue creations; serves the repository's labels."""
|
||||
@@ -40,9 +47,7 @@ class FakeGitea:
|
||||
def do_GET(self):
|
||||
assert self.headers["Authorization"] == f"token {TOKEN}"
|
||||
if self.path.startswith("/api/v1/repos/blueflare/alkane-toolkit/labels"):
|
||||
return self._json(200, [{"name": "bug", "id": 1}, {"name": "ui", "id": 2},
|
||||
{"name": "feature", "id": 3},
|
||||
{"name": "from-app", "id": 9}])
|
||||
return self._json(200, REPO_LABELS)
|
||||
self._json(404, {})
|
||||
|
||||
def do_POST(self):
|
||||
@@ -58,6 +63,23 @@ class FakeGitea:
|
||||
self.server = ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
||||
# Block until the serve_forever thread is actually handling requests, so
|
||||
# the relay's first label fetch cannot race server startup. The socket
|
||||
# listens from __init__, but under load the daemon thread can be starved
|
||||
# past the relay's HTTP timeout, which silently drops labels to [] and
|
||||
# made the first test flaky in CI.
|
||||
probe = urllib.request.Request(
|
||||
self.url + "/api/v1/repos/blueflare/alkane-toolkit/labels",
|
||||
headers={"Authorization": f"token {TOKEN}"})
|
||||
deadline = time.monotonic() + 5
|
||||
while True:
|
||||
try:
|
||||
urllib.request.urlopen(probe, timeout=1).read()
|
||||
break
|
||||
except Exception:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.02)
|
||||
|
||||
def close(self):
|
||||
self.server.shutdown()
|
||||
@@ -70,8 +92,18 @@ class RelayTests(unittest.TestCase):
|
||||
self.now = [1000.0]
|
||||
self.limiter = relay.RateLimiter(2, 3, clock=lambda: self.now[0])
|
||||
self.logs = []
|
||||
r = relay.Relay(relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN),
|
||||
self.limiter, log=self.logs.append)
|
||||
client = relay.Gitea(self.gitea.url, "blueflare/alkane-toolkit", TOKEN)
|
||||
# Seed the relay client's label cache directly from REPO_LABELS instead
|
||||
# of letting a request handler fetch it live. Gitea.label_ids() caches
|
||||
# for 10 minutes and silently falls back to [] on any fetch error; in CI
|
||||
# that first live GET -- a second server-to-server hop made from inside
|
||||
# the relay's own request thread -- failed reliably and dropped the
|
||||
# labels to [], while the issue-filing POST on the same path still
|
||||
# worked. Seeding the cache keeps label resolution deterministic (the
|
||||
# name->id mapping is still exercised) and leaves the issue POST live.
|
||||
client.labels = {label["name"]: label["id"] for label in REPO_LABELS}
|
||||
client.labels_at = time.monotonic()
|
||||
r = relay.Relay(client, self.limiter, log=self.logs.append)
|
||||
self.server = ThreadingHTTPServer(("127.0.0.1", 0), relay.make_handler(r))
|
||||
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
||||
self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
|
||||
|
||||
Reference in New Issue
Block a user