| 1 | use std::fs; |
| 2 | use std::io::{BufReader, Read}; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::process::{Child, Command, ExitStatus, Stdio}; |
| 5 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 6 | use std::sync::{Arc, Mutex}; |
| 7 | use std::thread; |
| 8 | use std::time::{Duration, Instant}; |
| 9 | |
| 10 | use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel}; |
| 11 | |
| 12 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 13 | pub enum Level { |
| 14 | V1, |
| 15 | V3, |
| 16 | } |
| 17 | |
| 18 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 19 | pub enum Job { |
| 20 | LinuxStart, |
| 21 | Linux(Level), |
| 22 | Server, |
| 23 | WindowsStart, |
| 24 | Windows(Level), |
| 25 | } |
| 26 | |
| 27 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 28 | pub enum Lane { |
| 29 | Host, |
| 30 | Vm, |
| 31 | } |
| 32 | |
| 33 | pub const LANES: [(Lane, &[Job]); 2] = [ |
| 34 | ( |
| 35 | Lane::Host, |
| 36 | &[ |
| 37 | Job::LinuxStart, |
| 38 | Job::Server, |
| 39 | Job::Linux(Level::V1), |
| 40 | Job::Linux(Level::V3), |
| 41 | ], |
| 42 | ), |
| 43 | ( |
| 44 | Lane::Vm, |
| 45 | &[ |
| 46 | Job::WindowsStart, |
| 47 | Job::Windows(Level::V1), |
| 48 | Job::Windows(Level::V3), |
| 49 | ], |
| 50 | ), |
| 51 | ]; |
| 52 | |
| 53 | type Slot = Arc<Mutex<Option<Child>>>; |
| 54 | |
| 55 | #[derive(Debug, Clone, PartialEq)] |
| 56 | pub enum Event { |
| 57 | Started(Job), |
| 58 | Progress { job: Job, done: u32, total: u32 }, |
| 59 | Line(Job, String), |
| 60 | Built(Job, PathBuf), |
| 61 | Finished(Job), |
| 62 | Skipped(Job, String), |
| 63 | Failed(Job, String), |
| 64 | Done, |
| 65 | } |
| 66 | |
| 67 | const LINUX: &str = "yumush-linux"; |
| 68 | const LINUX_IMAGE: &str = "docker.io/library/ubuntu:24.04"; |
| 69 | const LINUX_CACHE: &str = ".cache/yumush-build"; |
| 70 | const LINUX_PACKAGES: &str = "ca-certificates curl git build-essential pkg-config clang cmake nasm libpipewire-0.3-dev libspa-0.2-dev libva-dev libdrm-dev libgbm-dev libxkbcommon-x11-dev libxkbcommon-dev libxcb1-dev libwayland-dev libvulkan-dev libfontconfig-dev libfreetype-dev libasound2-dev"; |
| 71 | const ARCHIVE: &str = "dist/source.tgz"; |
| 72 | const VM: &str = "yumush-win"; |
| 73 | const VM_DIR: &str = "vm/yumush-win"; |
| 74 | const SSH_WAIT: Duration = Duration::from_secs(3 * 60 * 60); |
| 75 | const VM_IMAGE: &str = "docker.io/dockurr/windows"; |
| 76 | const VM_AUDIO: &str = "ARGUMENTS=-audiodev none,id=snd0 -device ich9-intel-hda,id=hda1 -device hda-duplex,bus=hda1.0,audiodev=snd0 -device ich9-intel-hda,id=hda2 -device hda-duplex,bus=hda2.0,audiodev=snd0"; |
| 77 | const INSTALL: &str = include_str!("release/install.bat"); |
| 78 | const TARGET: &str = "yumush@127.0.0.1"; |
| 79 | const PORT: &str = "2222"; |
| 80 | const EXTRACT: &str = "Remove-Item -Recurse -Force release -ErrorAction SilentlyContinue; New-Item -ItemType Directory release | Out-Null; tar -xmzf release.tgz -C release"; |
| 81 | |
| 82 | static RUNNING: AtomicBool = AtomicBool::new(false); |
| 83 | |
| 84 | pub fn running() -> bool { |
| 85 | RUNNING.load(Ordering::SeqCst) |
| 86 | } |
| 87 | |
| 88 | struct Running; |
| 89 | |
| 90 | impl Running { |
| 91 | fn new() -> Self { |
| 92 | RUNNING.store(true, Ordering::SeqCst); |
| 93 | Self |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | impl Drop for Running { |
| 98 | fn drop(&mut self) { |
| 99 | RUNNING.store(false, Ordering::SeqCst); |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | pub fn is_source(path: &Path) -> bool { |
| 104 | path.join("crates/client/Cargo.toml").is_file() && path.join(".git").exists() |
| 105 | } |
| 106 | |
| 107 | pub struct Build { |
| 108 | cancel: Arc<AtomicBool>, |
| 109 | children: Vec<Slot>, |
| 110 | retries: Vec<Arc<AtomicBool>>, |
| 111 | } |
| 112 | |
| 113 | impl Build { |
| 114 | pub fn start(source: PathBuf) -> (Self, UnboundedReceiver<Event>) { |
| 115 | let (tx, rx) = unbounded_channel(); |
| 116 | let build = Self { |
| 117 | cancel: Arc::default(), |
| 118 | children: LANES.iter().map(|_| Slot::default()).collect(), |
| 119 | retries: LANES.iter().map(|_| Arc::default()).collect(), |
| 120 | }; |
| 121 | let lanes: Vec<Cx> = build |
| 122 | .children |
| 123 | .iter() |
| 124 | .zip(&build.retries) |
| 125 | .map(|(child, retry)| Cx { |
| 126 | tx: tx.clone(), |
| 127 | cancel: build.cancel.clone(), |
| 128 | child: child.clone(), |
| 129 | retry: retry.clone(), |
| 130 | }) |
| 131 | .collect(); |
| 132 | let running = Running::new(); |
| 133 | thread::spawn(move || { |
| 134 | let _running = running; |
| 135 | run(&source, &lanes); |
| 136 | }); |
| 137 | (build, rx) |
| 138 | } |
| 139 | |
| 140 | pub fn retry(&self, job: Job) { |
| 141 | if let Some(lane) = LANES.iter().position(|(_, jobs)| jobs.contains(&job)) { |
| 142 | self.retries[lane].store(true, Ordering::SeqCst); |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | pub fn cancel(&self) { |
| 147 | self.cancel.store(true, Ordering::SeqCst); |
| 148 | podman_ok(&["stop", "-t", "2", LINUX]); |
| 149 | for slot in &self.children { |
| 150 | if let Some(child) = slot.lock().unwrap().as_mut() { |
| 151 | let _ = child.kill(); |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | #[derive(Clone)] |
| 158 | struct Cx { |
| 159 | tx: UnboundedSender<Event>, |
| 160 | cancel: Arc<AtomicBool>, |
| 161 | child: Slot, |
| 162 | retry: Arc<AtomicBool>, |
| 163 | } |
| 164 | |
| 165 | impl Cx { |
| 166 | fn wait_retry(&self) -> bool { |
| 167 | while !self.cancelled() { |
| 168 | if self.retry.swap(false, Ordering::SeqCst) { |
| 169 | return true; |
| 170 | } |
| 171 | thread::sleep(Duration::from_millis(200)); |
| 172 | } |
| 173 | false |
| 174 | } |
| 175 | |
| 176 | fn send(&self, event: Event) { |
| 177 | let _ = self.tx.send(event); |
| 178 | } |
| 179 | |
| 180 | fn cancelled(&self) -> bool { |
| 181 | self.cancel.load(Ordering::SeqCst) |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | fn run(source: &Path, lanes: &[Cx]) { |
| 186 | let key = vm_dir().join("id_ed25519"); |
| 187 | let first = &lanes[0]; |
| 188 | let _lock = match lock() { |
| 189 | Ok(lock) => lock, |
| 190 | Err(e) => { |
| 191 | first.send(Event::Failed(LANES[0].1[0], e)); |
| 192 | first.send(Event::Done); |
| 193 | return; |
| 194 | } |
| 195 | }; |
| 196 | let vm_was_running = match preflight(source) { |
| 197 | Ok(running) => running, |
| 198 | Err(e) => { |
| 199 | first.send(Event::Failed(LANES[0].1[0], e)); |
| 200 | first.send(Event::Done); |
| 201 | return; |
| 202 | } |
| 203 | }; |
| 204 | thread::scope(|scope| { |
| 205 | for ((_, jobs), cx) in LANES.iter().zip(lanes) { |
| 206 | let key = &key; |
| 207 | scope.spawn(move || run_lane(jobs, source, key, cx)); |
| 208 | } |
| 209 | }); |
| 210 | if !vm_was_running { |
| 211 | podman_ok(&["stop", VM]); |
| 212 | } |
| 213 | podman_ok(&["stop", "-t", "2", LINUX]); |
| 214 | first.send(Event::Done); |
| 215 | } |
| 216 | |
| 217 | fn run_lane(jobs: &[Job], source: &Path, key: &Path, cx: &Cx) { |
| 218 | let mut next = 0; |
| 219 | while let Some(&job) = jobs.get(next) { |
| 220 | if cx.cancelled() { |
| 221 | cx.send(Event::Failed(job, "cancelled".into())); |
| 222 | return; |
| 223 | } |
| 224 | match run_job(job, source, key, cx) { |
| 225 | Ok(()) => next += 1, |
| 226 | Err(_) if cx.cancelled() => { |
| 227 | cx.send(Event::Failed(job, "cancelled".into())); |
| 228 | return; |
| 229 | } |
| 230 | Err(e) => { |
| 231 | cx.send(Event::Failed(job, e)); |
| 232 | if !cx.wait_retry() { |
| 233 | return; |
| 234 | } |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | fn lock() -> Result<fs::File, String> { |
| 241 | let cache = linux_cache(); |
| 242 | fs::create_dir_all(&cache).map_err(|e| e.to_string())?; |
| 243 | let file = fs::File::create(cache.join("build.lock")).map_err(|e| e.to_string())?; |
| 244 | file.try_lock() |
| 245 | .map_err(|_| "another build is running".to_string())?; |
| 246 | Ok(file) |
| 247 | } |
| 248 | |
| 249 | fn preflight(source: &Path) -> Result<bool, String> { |
| 250 | let dirty = Command::new("git") |
| 251 | .arg("-C") |
| 252 | .arg(source) |
| 253 | .args(["status", "--porcelain"]) |
| 254 | .output() |
| 255 | .map_err(|e| e.to_string())?; |
| 256 | if !dirty.stdout.is_empty() { |
| 257 | return Err("uncommitted changes".into()); |
| 258 | } |
| 259 | snapshot(source)?; |
| 260 | Ok(container_running(VM)) |
| 261 | } |
| 262 | |
| 263 | fn container_running(container: &str) -> bool { |
| 264 | podman() |
| 265 | .args(["inspect", "-f", "{{.State.Running}}", container]) |
| 266 | .output() |
| 267 | .is_ok_and(|out| String::from_utf8_lossy(&out.stdout).trim() == "true") |
| 268 | } |
| 269 | |
| 270 | fn run_job(job: Job, source: &Path, key: &Path, cx: &Cx) -> Result<(), String> { |
| 271 | match job { |
| 272 | Job::LinuxStart => { |
| 273 | if !cfg!(target_os = "linux") { |
| 274 | return skip(cx, job, "not linux"); |
| 275 | } |
| 276 | cx.send(Event::Started(job)); |
| 277 | start_linux(job, source, cx) |
| 278 | } |
| 279 | Job::Linux(level) => { |
| 280 | if !cfg!(target_os = "linux") { |
| 281 | return skip(cx, job, "not linux"); |
| 282 | } |
| 283 | cx.send(Event::Started(job)); |
| 284 | build_linux(job, level, source, cx) |
| 285 | } |
| 286 | Job::Server => { |
| 287 | if !cfg!(target_os = "linux") { |
| 288 | return skip(cx, job, "not linux"); |
| 289 | } |
| 290 | cx.send(Event::Started(job)); |
| 291 | build_server(job, source, cx) |
| 292 | } |
| 293 | Job::WindowsStart => { |
| 294 | if !cfg!(target_os = "linux") { |
| 295 | return skip(cx, job, "not linux"); |
| 296 | } |
| 297 | cx.send(Event::Started(job)); |
| 298 | start_windows(job, source, key, cx) |
| 299 | } |
| 300 | Job::Windows(level) => { |
| 301 | cx.send(Event::Started(job)); |
| 302 | build_windows(job, level, source, key, cx) |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | fn skip(cx: &Cx, job: Job, why: &str) -> Result<(), String> { |
| 308 | cx.send(Event::Skipped(job, why.into())); |
| 309 | Ok(()) |
| 310 | } |
| 311 | |
| 312 | fn flags(level: Level) -> (&'static str, &'static str) { |
| 313 | match level { |
| 314 | Level::V1 => ("v1", "x86-64"), |
| 315 | Level::V3 => ("v3", "x86-64-v3"), |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | fn toml_text(cpu: &str) -> String { |
| 320 | format!( |
| 321 | "[target.'cfg(target_arch = \"x86_64\")']\nrustflags = [\"-C\", \"target-cpu={cpu}\"]\n" |
| 322 | ) |
| 323 | } |
| 324 | |
| 325 | fn snapshot(source: &Path) -> Result<(), String> { |
| 326 | fs::create_dir_all(source.join("dist")).map_err(|e| e.to_string())?; |
| 327 | check( |
| 328 | Command::new("git") |
| 329 | .arg("-C") |
| 330 | .arg(source) |
| 331 | .args(["archive", "--format=tar.gz", "-o"]) |
| 332 | .arg(source.join(ARCHIVE)) |
| 333 | .arg("HEAD"), |
| 334 | ) |
| 335 | } |
| 336 | |
| 337 | fn linux_cache() -> PathBuf { |
| 338 | dirs::home_dir().unwrap_or_default().join(LINUX_CACHE) |
| 339 | } |
| 340 | |
| 341 | fn host_rust() -> Result<String, String> { |
| 342 | let out = Command::new("rustc") |
| 343 | .arg("--version") |
| 344 | .output() |
| 345 | .map_err(|e| e.to_string())?; |
| 346 | String::from_utf8_lossy(&out.stdout) |
| 347 | .split_whitespace() |
| 348 | .nth(1) |
| 349 | .map(str::to_string) |
| 350 | .ok_or_else(|| "rustc version unknown".to_string()) |
| 351 | } |
| 352 | |
| 353 | fn in_linux(script: &str) -> Command { |
| 354 | let mut cmd = podman(); |
| 355 | cmd.args(["exec", "-w", "/build"]) |
| 356 | .args(["-e", "PATH=/root/.cargo/bin:/usr/local/bin:/usr/bin:/bin"]) |
| 357 | .args(["-e", "DEBIAN_FRONTEND=noninteractive"]) |
| 358 | .args(["-e", "CARGO_TERM_PROGRESS_WHEN=always"]) |
| 359 | .args(["-e", "CARGO_TERM_PROGRESS_WIDTH=200"]) |
| 360 | .args(["-e", "CARGO_TERM_COLOR=never"]) |
| 361 | .args([LINUX, "bash", "-ec", script]) |
| 362 | .stdout(Stdio::piped()); |
| 363 | cmd |
| 364 | } |
| 365 | |
| 366 | fn start_linux(job: Job, source: &Path, cx: &Cx) -> Result<(), String> { |
| 367 | let cache = linux_cache(); |
| 368 | for dir in ["cargo", "rustup", "target"] { |
| 369 | fs::create_dir_all(cache.join(dir)).map_err(|e| e.to_string())?; |
| 370 | } |
| 371 | if !podman_ok(&["container", "exists", LINUX]) { |
| 372 | cx.send(Event::Line(job, "creating container".into())); |
| 373 | let mount = |dir: &str, at: &str| format!("{}:{at}:Z", cache.join(dir).display()); |
| 374 | check( |
| 375 | podman() |
| 376 | .args(["run", "-d", "--name", LINUX]) |
| 377 | .args(["-v", &mount("cargo", "/root/.cargo")]) |
| 378 | .args(["-v", &mount("rustup", "/root/.rustup")]) |
| 379 | .args(["-v", &mount("target", "/build/target")]) |
| 380 | .args([LINUX_IMAGE, "sleep", "infinity"]), |
| 381 | )?; |
| 382 | } else { |
| 383 | check(podman().args(["start", LINUX]))?; |
| 384 | } |
| 385 | check( |
| 386 | podman() |
| 387 | .arg("cp") |
| 388 | .arg(source.join(ARCHIVE)) |
| 389 | .arg(format!("{LINUX}:/build/src.tgz")), |
| 390 | )?; |
| 391 | let rust = host_rust()?; |
| 392 | let script = format!( |
| 393 | "[ -f /etc/yumush-ready ] || {{ apt-get update; apt-get install -y --no-install-recommends {LINUX_PACKAGES}; touch /etc/yumush-ready; }} |
| 394 | [ -x /root/.cargo/bin/rustup ] || curl -sSf https://sh.rustup.rs | sh -s -- -y --no-modify-path --default-toolchain none |
| 395 | rustup toolchain install {rust} --profile minimal |
| 396 | rustup default {rust} |
| 397 | rm -rf src && mkdir src && tar -xmzf src.tgz -C src" |
| 398 | ); |
| 399 | stream(&mut in_linux(&script), job, cx)?; |
| 400 | cx.send(Event::Finished(job)); |
| 401 | Ok(()) |
| 402 | } |
| 403 | |
| 404 | fn build_in_linux( |
| 405 | job: Job, |
| 406 | package: &str, |
| 407 | level: Level, |
| 408 | dest: &str, |
| 409 | source: &Path, |
| 410 | cx: &Cx, |
| 411 | ) -> Result<(), String> { |
| 412 | let (name, cpu) = flags(level); |
| 413 | let script = format!( |
| 414 | "cd src |
| 415 | rm -f /build/target/release-{name}/release/{package} |
| 416 | cargo build --release -p {package} --target-dir /build/target/release-{name} --config 'target.x86_64-unknown-linux-gnu.rustflags=[\"-C\", \"target-cpu={cpu}\"]'" |
| 417 | ); |
| 418 | stream(&mut in_linux(&script), job, cx)?; |
| 419 | let built = linux_cache().join(format!("target/release-{name}/release/{package}")); |
| 420 | let dest = source.join("dist").join(dest); |
| 421 | fs::copy(&built, &dest).map_err(|e| e.to_string())?; |
| 422 | cx.send(Event::Built(job, dest)); |
| 423 | cx.send(Event::Finished(job)); |
| 424 | Ok(()) |
| 425 | } |
| 426 | |
| 427 | fn build_linux(job: Job, level: Level, source: &Path, cx: &Cx) -> Result<(), String> { |
| 428 | let (name, _) = flags(level); |
| 429 | build_in_linux( |
| 430 | job, |
| 431 | "client", |
| 432 | level, |
| 433 | &format!("x86_64_{name}-linux"), |
| 434 | source, |
| 435 | cx, |
| 436 | ) |
| 437 | } |
| 438 | |
| 439 | fn build_server(job: Job, source: &Path, cx: &Cx) -> Result<(), String> { |
| 440 | build_in_linux( |
| 441 | job, |
| 442 | "server", |
| 443 | Level::V1, |
| 444 | common::update::SERVER_TARGET, |
| 445 | source, |
| 446 | cx, |
| 447 | ) |
| 448 | } |
| 449 | |
| 450 | fn vm_dir() -> PathBuf { |
| 451 | dirs::home_dir().unwrap_or_default().join(VM_DIR) |
| 452 | } |
| 453 | |
| 454 | fn create_windows(job: Job, key: &Path, cx: &Cx) -> Result<(), String> { |
| 455 | if !Path::new("/dev/kvm").exists() { |
| 456 | return Err("no /dev/kvm".into()); |
| 457 | } |
| 458 | let dir = vm_dir(); |
| 459 | for sub in ["storage", "oem", "shared"] { |
| 460 | fs::create_dir_all(dir.join(sub)).map_err(|e| e.to_string())?; |
| 461 | } |
| 462 | if !key.exists() { |
| 463 | check( |
| 464 | Command::new("ssh-keygen") |
| 465 | .args(["-q", "-t", "ed25519", "-N", "", "-C", "yumush-vm", "-f"]) |
| 466 | .arg(key), |
| 467 | )?; |
| 468 | } |
| 469 | let _ = Command::new("chattr") |
| 470 | .arg("+C") |
| 471 | .arg(dir.join("storage")) |
| 472 | .output(); |
| 473 | let public = fs::read_to_string(key.with_extension("pub")).map_err(|e| e.to_string())?; |
| 474 | fs::write( |
| 475 | dir.join("oem/install.bat"), |
| 476 | INSTALL.replace("{key}", public.trim()), |
| 477 | ) |
| 478 | .map_err(|e| e.to_string())?; |
| 479 | let cores = thread::available_parallelism().map_or(4, |n| n.get()); |
| 480 | let mount = |sub: &str| format!("{}:/{sub}:Z", dir.join(sub).display()); |
| 481 | cx.send(Event::Line(job, "creating Windows VM".into())); |
| 482 | check( |
| 483 | podman() |
| 484 | .args(["run", "-d", "--name", VM]) |
| 485 | .args([ |
| 486 | "-e", |
| 487 | "VERSION=11l", |
| 488 | "-e", |
| 489 | "RAM_SIZE=12G", |
| 490 | "-e", |
| 491 | "DISK_SIZE=96G", |
| 492 | ]) |
| 493 | .args(["-e", &format!("CPU_CORES={cores}")]) |
| 494 | .args([ |
| 495 | "-e", |
| 496 | "USERNAME=yumush", |
| 497 | "-e", |
| 498 | "PASSWORD=yumush", |
| 499 | "-e", |
| 500 | "USER_PORTS=22", |
| 501 | ]) |
| 502 | .args(["-e", VM_AUDIO]) |
| 503 | .args([ |
| 504 | "--device", |
| 505 | "/dev/kvm", |
| 506 | "--device", |
| 507 | "/dev/net/tun", |
| 508 | "--cap-add", |
| 509 | "NET_ADMIN", |
| 510 | ]) |
| 511 | .args(["-p", "127.0.0.1:8006:8006", "-p", "127.0.0.1:3389:3389"]) |
| 512 | .args(["-p", &format!("127.0.0.1:{PORT}:22")]) |
| 513 | .args([ |
| 514 | "-v", |
| 515 | &mount("storage"), |
| 516 | "-v", |
| 517 | &mount("oem"), |
| 518 | "-v", |
| 519 | &mount("shared"), |
| 520 | ]) |
| 521 | .args(["--stop-timeout", "120", VM_IMAGE]), |
| 522 | ) |
| 523 | } |
| 524 | |
| 525 | fn start_windows(job: Job, source: &Path, key: &Path, cx: &Cx) -> Result<(), String> { |
| 526 | if !podman_ok(&["container", "exists", VM]) { |
| 527 | create_windows(job, key, cx)?; |
| 528 | } else if !container_running(VM) { |
| 529 | check(podman().args(["start", VM]))?; |
| 530 | } |
| 531 | wait_ssh(job, key, cx)?; |
| 532 | while !ssh_ok_with( |
| 533 | key, |
| 534 | "if (Test-Path C:\\OEM\\finished.txt) { exit 0 } else { exit 1 }", |
| 535 | ) { |
| 536 | if cx.cancelled() { |
| 537 | return Err("cancelled".into()); |
| 538 | } |
| 539 | cx.send(Event::Line(job, "installing build tools".into())); |
| 540 | thread::sleep(Duration::from_secs(15)); |
| 541 | } |
| 542 | let rust = host_rust()?; |
| 543 | stream( |
| 544 | &mut ps( |
| 545 | key, |
| 546 | &format!( |
| 547 | "$env:Path += \";$env:USERPROFILE\\.cargo\\bin\"\nrustup toolchain install {rust} --profile minimal\nrustup default {rust}" |
| 548 | ), |
| 549 | ), |
| 550 | job, |
| 551 | cx, |
| 552 | )?; |
| 553 | check( |
| 554 | scp(key) |
| 555 | .arg(source.join(ARCHIVE)) |
| 556 | .arg(format!("{TARGET}:release.tgz")), |
| 557 | )?; |
| 558 | stream(&mut ps(key, EXTRACT), job, cx)?; |
| 559 | cx.send(Event::Finished(job)); |
| 560 | Ok(()) |
| 561 | } |
| 562 | |
| 563 | fn build_windows(job: Job, level: Level, source: &Path, key: &Path, cx: &Cx) -> Result<(), String> { |
| 564 | let (name, cpu) = flags(level); |
| 565 | let script = format!( |
| 566 | r#"$ErrorActionPreference = 'Continue' |
| 567 | Set-Location release |
| 568 | $env:Path += ";$env:USERPROFILE\.cargo\bin" |
| 569 | $env:CARGO_TERM_PROGRESS_WHEN = 'always'; $env:CARGO_TERM_PROGRESS_WIDTH = '200'; $env:CARGO_TERM_COLOR = 'never' |
| 570 | @' |
| 571 | {toml}'@ | Set-Content -Encoding ascii level.toml |
| 572 | Remove-Item -Force ..\target-release-{name}\release\client.exe -ErrorAction SilentlyContinue |
| 573 | cargo build --release -p client --target-dir ..\target-release-{name} --config level.toml |
| 574 | exit $LASTEXITCODE |
| 575 | "#, |
| 576 | toml = toml_text(cpu) |
| 577 | ); |
| 578 | stream(&mut ps(key, &script), job, cx)?; |
| 579 | let dest = source.join("dist").join(format!("x86_64_{name}-windows")); |
| 580 | check( |
| 581 | scp(key) |
| 582 | .arg(format!("{TARGET}:target-release-{name}/release/client.exe")) |
| 583 | .arg(&dest), |
| 584 | )?; |
| 585 | cx.send(Event::Built(job, dest)); |
| 586 | cx.send(Event::Finished(job)); |
| 587 | Ok(()) |
| 588 | } |
| 589 | |
| 590 | fn wait_ssh(job: Job, key: &Path, cx: &Cx) -> Result<(), String> { |
| 591 | let deadline = Instant::now() + SSH_WAIT; |
| 592 | while !ssh_ok(key) { |
| 593 | if cx.cancelled() { |
| 594 | return Err("cancelled".into()); |
| 595 | } |
| 596 | if Instant::now() >= deadline { |
| 597 | return Err("ssh timeout".into()); |
| 598 | } |
| 599 | cx.send(Event::Line(job, vm_status())); |
| 600 | thread::sleep(Duration::from_secs(5)); |
| 601 | } |
| 602 | Ok(()) |
| 603 | } |
| 604 | |
| 605 | fn vm_status() -> String { |
| 606 | let Ok(out) = podman().args(["logs", "--tail", "5", VM]).output() else { |
| 607 | return "waiting for ssh".into(); |
| 608 | }; |
| 609 | let text = String::from_utf8_lossy(&out.stdout) + String::from_utf8_lossy(&out.stderr); |
| 610 | text.lines() |
| 611 | .map(plain) |
| 612 | .rfind(|line| !line.is_empty() && !line.starts_with("Warning")) |
| 613 | .unwrap_or_else(|| "waiting for ssh".into()) |
| 614 | } |
| 615 | |
| 616 | fn plain(line: &str) -> String { |
| 617 | let mut out = String::new(); |
| 618 | let mut chars = line.chars(); |
| 619 | while let Some(c) = chars.next() { |
| 620 | if c == '\u{1b}' { |
| 621 | chars.by_ref().find(|c| c.is_ascii_alphabetic()); |
| 622 | } else if c != '❯' { |
| 623 | out.push(c); |
| 624 | } |
| 625 | } |
| 626 | out.trim().trim_end_matches("...").to_string() |
| 627 | } |
| 628 | |
| 629 | fn opts(key: &Path, port_flag: &str) -> Vec<String> { |
| 630 | let mut args = vec!["-i".to_string(), key.display().to_string()]; |
| 631 | for option in [ |
| 632 | "StrictHostKeyChecking=no", |
| 633 | "UserKnownHostsFile=/dev/null", |
| 634 | "ConnectTimeout=10", |
| 635 | "LogLevel=ERROR", |
| 636 | ] { |
| 637 | args.push("-o".into()); |
| 638 | args.push(option.into()); |
| 639 | } |
| 640 | args.push(port_flag.into()); |
| 641 | args.push(PORT.into()); |
| 642 | args |
| 643 | } |
| 644 | |
| 645 | fn ssh(key: &Path) -> Command { |
| 646 | let mut cmd = Command::new("ssh"); |
| 647 | cmd.args(opts(key, "-p")).arg(TARGET); |
| 648 | cmd |
| 649 | } |
| 650 | |
| 651 | fn scp(key: &Path) -> Command { |
| 652 | let mut cmd = Command::new("scp"); |
| 653 | cmd.arg("-q").args(opts(key, "-P")); |
| 654 | cmd |
| 655 | } |
| 656 | |
| 657 | fn ps(key: &Path, script: &str) -> Command { |
| 658 | let script = format!("$ProgressPreference = 'SilentlyContinue'\n{script}"); |
| 659 | let bytes: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect(); |
| 660 | let mut cmd = ssh(key); |
| 661 | cmd.args([ |
| 662 | "powershell", |
| 663 | "-NoProfile", |
| 664 | "-NonInteractive", |
| 665 | "-EncodedCommand", |
| 666 | ]) |
| 667 | .arg(base64(&bytes)) |
| 668 | .stdout(Stdio::piped()); |
| 669 | cmd |
| 670 | } |
| 671 | |
| 672 | fn ssh_ok(key: &Path) -> bool { |
| 673 | ssh_ok_with(key, "echo ok") |
| 674 | } |
| 675 | |
| 676 | fn ssh_ok_with(key: &Path, command: &str) -> bool { |
| 677 | ssh(key) |
| 678 | .arg(command) |
| 679 | .stdout(Stdio::null()) |
| 680 | .stderr(Stdio::null()) |
| 681 | .status() |
| 682 | .is_ok_and(|s| s.success()) |
| 683 | } |
| 684 | |
| 685 | fn podman() -> Command { |
| 686 | let mut cmd = Command::new("podman"); |
| 687 | if let Some(runtime) = std::env::var_os("XDG_RUNTIME_DIR") { |
| 688 | let mut bus = std::ffi::OsString::from("unix:path="); |
| 689 | bus.push(runtime); |
| 690 | bus.push("/bus"); |
| 691 | cmd.env("DBUS_SESSION_BUS_ADDRESS", bus); |
| 692 | } |
| 693 | cmd |
| 694 | } |
| 695 | |
| 696 | fn podman_ok(args: &[&str]) -> bool { |
| 697 | podman() |
| 698 | .args(args) |
| 699 | .stdout(Stdio::null()) |
| 700 | .stderr(Stdio::null()) |
| 701 | .status() |
| 702 | .is_ok_and(|s| s.success()) |
| 703 | } |
| 704 | |
| 705 | fn check(cmd: &mut Command) -> Result<(), String> { |
| 706 | let out = cmd.output().map_err(|e| e.to_string())?; |
| 707 | if out.status.success() { |
| 708 | Ok(()) |
| 709 | } else { |
| 710 | let stderr = String::from_utf8_lossy(&out.stderr); |
| 711 | Err(stderr |
| 712 | .lines() |
| 713 | .rev() |
| 714 | .find(|line| !line.trim().is_empty()) |
| 715 | .unwrap_or_default() |
| 716 | .trim() |
| 717 | .to_string()) |
| 718 | } |
| 719 | } |
| 720 | |
| 721 | fn stream(cmd: &mut Command, job: Job, cx: &Cx) -> Result<(), String> { |
| 722 | let mut child = cmd |
| 723 | .stderr(Stdio::piped()) |
| 724 | .spawn() |
| 725 | .map_err(|e| e.to_string())?; |
| 726 | let stdout = child.stdout.take(); |
| 727 | let stderr = child.stderr.take(); |
| 728 | *cx.child.lock().unwrap() = Some(child); |
| 729 | let out = stdout.map(|o| { |
| 730 | let cx = cx.clone(); |
| 731 | thread::spawn(move || pump(o, job, &cx)) |
| 732 | }); |
| 733 | let err = stderr.map(|e| pump(e, job, cx)).unwrap_or_default(); |
| 734 | if let Some(out) = out { |
| 735 | let _ = out.join(); |
| 736 | } |
| 737 | let status = wait(cx)?; |
| 738 | if status.success() { |
| 739 | return Ok(()); |
| 740 | } |
| 741 | Err(if err.is_empty() { |
| 742 | format!("exit {status}") |
| 743 | } else { |
| 744 | err |
| 745 | }) |
| 746 | } |
| 747 | |
| 748 | fn wait(cx: &Cx) -> Result<ExitStatus, String> { |
| 749 | loop { |
| 750 | let mut slot = cx.child.lock().unwrap(); |
| 751 | if cx.cancelled() |
| 752 | && let Some(child) = slot.as_mut() |
| 753 | { |
| 754 | let _ = child.kill(); |
| 755 | } |
| 756 | let Some(child) = slot.as_mut() else { |
| 757 | return Err("no child".into()); |
| 758 | }; |
| 759 | if let Some(status) = child.try_wait().map_err(|e| e.to_string())? { |
| 760 | return Ok(status); |
| 761 | } |
| 762 | drop(slot); |
| 763 | thread::sleep(Duration::from_millis(100)); |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | fn pump(reader: impl Read, job: Job, cx: &Cx) -> String { |
| 768 | let mut last = String::new(); |
| 769 | let mut piece = Vec::new(); |
| 770 | for byte in BufReader::new(reader) |
| 771 | .bytes() |
| 772 | .map_while(Result::ok) |
| 773 | .chain(*b"\n") |
| 774 | { |
| 775 | if byte != b'\r' && byte != b'\n' { |
| 776 | piece.push(byte); |
| 777 | continue; |
| 778 | } |
| 779 | let text = String::from_utf8_lossy(&piece).trim().to_string(); |
| 780 | piece.clear(); |
| 781 | if text.is_empty() { |
| 782 | continue; |
| 783 | } |
| 784 | cx.send(progress(job, &text).unwrap_or_else(|| Event::Line(job, text.clone()))); |
| 785 | last = text; |
| 786 | } |
| 787 | last |
| 788 | } |
| 789 | |
| 790 | fn progress(job: Job, text: &str) -> Option<Event> { |
| 791 | let rest = text.split_once("Building [")?.1.split_once(']')?.1; |
| 792 | let (done, total) = rest.trim_start().split(':').next()?.split_once('/')?; |
| 793 | Some(Event::Progress { |
| 794 | job, |
| 795 | done: done.trim().parse().ok()?, |
| 796 | total: total.trim().parse().ok()?, |
| 797 | }) |
| 798 | } |
| 799 | |
| 800 | fn base64(bytes: &[u8]) -> String { |
| 801 | const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 802 | let mut out = String::new(); |
| 803 | for chunk in bytes.chunks(3) { |
| 804 | let n = chunk |
| 805 | .iter() |
| 806 | .enumerate() |
| 807 | .fold(0u32, |n, (i, &b)| n | (b as u32) << (16 - 8 * i)); |
| 808 | for i in 0..4 { |
| 809 | if i <= chunk.len() { |
| 810 | out.push(TABLE[(n >> (18 - 6 * i)) as usize & 63] as char); |
| 811 | } else { |
| 812 | out.push('='); |
| 813 | } |
| 814 | } |
| 815 | } |
| 816 | out |
| 817 | } |