diff --git a/.forge/ci.toml b/.forge/ci.toml new file mode 100644 index 0000000..e6c6f06 --- /dev/null +++ b/.forge/ci.toml @@ -0,0 +1,32 @@ +# CI for forge itself. Format: docs/ci.md, parser: crates/forge-ci/src/config.rs. +# +# cmake is needed because aws-lc-sys (via aws-lc-rs, pulled in by rustls) builds its C +# sources with cmake. The rust image has a C compiler but not cmake. +# The workflow has no branch condition, so the build job also runs for pull requests. + +[on] +push = ["main"] +pull_request = true +manual = true + +[jobs.test] +image = "docker.io/library/rust:1" +run = """ +apt-get update +apt-get install -y --no-install-recommends cmake +cargo test --workspace +""" +timeout_minutes = 60 + +[jobs.build] +image = "docker.io/library/rust:1" +needs = ["test"] +run = """ +apt-get update +apt-get install -y --no-install-recommends cmake +cargo build --profile dist -p forge-web +mkdir -p dist +cp target/dist/forge dist/forge +""" +artifacts = ["dist/forge"] +timeout_minutes = 60 diff --git a/Cargo.toml b/Cargo.toml index 9c49957..49b43ca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -114,6 +114,10 @@ similar = "3.2.0" semver = "1.0.28" zip = { version = "9.0.3", default-features = false, features = ["deflate"] } +[profile.dev.package.sha2] +# self-update hashes the ~1 GB debug binary at boot; unoptimized sha2 takes ~26 s. +opt-level = 3 + [profile.release] lto = true codegen-units = 1 diff --git a/config/forge.example.toml b/config/forge.example.toml index 07683b9..c61e2d9 100644 --- a/config/forge.example.toml +++ b/config/forge.example.toml @@ -110,3 +110,18 @@ trusted_proxies = [] # [orgs] # Who may create organizations: "all" (any signed-in person) or "admin" (instance admins only). # creation = "all" + +# Self-update (off by default). When enabled, a successful push run of `repo` on `branch` replaces +# the running binary with the artifact of `job` and restarts. Run under systemd with Restart=on-failure, +# because the process exits with code 75 after the swap. A sha256 listed in `.bad` is never installed. +# [self_update] +# Whether a green run deploys its artifact. +# enabled = false +# The repo whose runs deploy, as owner/name. +# repo = "Tahinli/forge" +# The branch whose push runs deploy. +# branch = "main" +# The CI job that produces the artifact. +# job = "build" +# The artifact name produced by job. A single file. CI flattens paths, so dist/forge is stored as dist_forge. +# artifact = "dist_forge" diff --git a/crates/forge-core/migrations/0024_ci.sql b/crates/forge-core/migrations/0024_ci.sql index a332b94..c1caa56 100644 --- a/crates/forge-core/migrations/0024_ci.sql +++ b/crates/forge-core/migrations/0024_ci.sql @@ -1,6 +1,6 @@ -- CI: runners, registration tokens, runs, jobs, artifacts and sealed repo secrets. -- Runner, registration and job tokens are stored as sha256 hex only. Timestamps are RFC 3339 --- UTC stamps from time.rs. See docs/ci-interfaces.md section 2. +-- UTC stamps from time.rs. CREATE TABLE ci_runners ( id TEXT PRIMARY KEY, diff --git a/crates/forge-core/migrations/0031_advisories.sql b/crates/forge-core/migrations/0031_advisories.sql index e628eb4..d4b2a10 100644 --- a/crates/forge-core/migrations/0031_advisories.sql +++ b/crates/forge-core/migrations/0031_advisories.sql @@ -1,5 +1,5 @@ -- Security advisories (OSV dumps), the dependencies read from each repo's lockfiles, and the --- alerts that match them. See docs/wave-c-interfaces.md (A1). +-- alerts that match them. CREATE TABLE advisories ( id TEXT NOT NULL, ecosystem TEXT NOT NULL, diff --git a/crates/forge-core/migrations/0034_advisory_notifications.sql b/crates/forge-core/migrations/0034_advisory_notifications.sql index a7cbfee..14057ae 100644 --- a/crates/forge-core/migrations/0034_advisory_notifications.sql +++ b/crates/forge-core/migrations/0034_advisory_notifications.sql @@ -1,5 +1,4 @@ --- One inbox row per admin and repo, for security alerts a lockfile scan opened (see --- docs/wave-c-interfaces.md, F-A). Alerts are not issues, so they cannot use the `notifications` +-- One inbox row per admin and repo, for security alerts a lockfile scan opened. Alerts are not issues, so they cannot use the `notifications` -- table, which points at issues. `new_alerts` counts the alerts opened since the row was last read. CREATE TABLE advisory_notifications ( user_id TEXT NOT NULL REFERENCES users(id), diff --git a/crates/forge-core/src/config.rs b/crates/forge-core/src/config.rs index 7daf0ee..9d0af30 100644 --- a/crates/forge-core/src/config.rs +++ b/crates/forge-core/src/config.rs @@ -99,6 +99,65 @@ pub struct Config { /// Organization rules, from the `[orgs]` section. #[serde(default)] pub orgs: OrgsConfig, + /// Self-update after a green CI run of the forge's own repo, from the `[self_update]` section. + #[serde(default)] + pub self_update: SelfUpdateConfig, +} + +/// Self-update, from the `[self_update]` section. When enabled, a successful push run of `repo` +/// on `branch` replaces the running binary with the `artifact` of `job` and restarts. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields, default)] +pub struct SelfUpdateConfig { + /// Whether a green run deploys its artifact. Off by default. + pub enabled: bool, + /// The repo whose runs deploy, as `owner/name`. + pub repo: String, + /// The branch whose push runs deploy. + pub branch: String, + /// The CI job that produces the artifact. + pub job: String, + /// The artifact name produced by `job`. A single file. CI flattens paths, so `dist/forge` + /// is stored as `dist_forge`. + pub artifact: String, +} + +impl Default for SelfUpdateConfig { + fn default() -> Self { + SelfUpdateConfig { + enabled: false, + repo: String::new(), + branch: "main".into(), + job: "build".into(), + artifact: "dist_forge".into(), + } + } +} + +impl SelfUpdateConfig { + fn validate(&self) -> Result<()> { + if !self.enabled { + return Ok(()); + } + let parts: Vec<&str> = self.repo.split('/').collect(); + if parts.len() != 2 || parts.iter().any(|part| part.is_empty()) { + return Err(Error::Config( + "[self_update] repo must be owner/name when enabled".into(), + )); + } + for (field, value) in [ + ("branch", &self.branch), + ("job", &self.job), + ("artifact", &self.artifact), + ] { + if value.trim().is_empty() { + return Err(Error::Config(format!( + "[self_update] {field} must not be empty when enabled" + ))); + } + } + Ok(()) + } } /// Organization rules, from the `[orgs]` section. @@ -299,7 +358,7 @@ impl Default for ReleasesConfig { } } -/// Scheduled backups, from the `[backup]` section. See `docs/backup-interfaces.md`. +/// Scheduled backups, from the `[backup]` section. See `docs/backup.md`. #[derive(Debug, Clone, Deserialize)] #[serde(deny_unknown_fields, default)] pub struct BackupConfig { @@ -395,6 +454,7 @@ impl Config { toml::from_str(&text).map_err(|e| Error::Config(format!("{}: {e}", path.display())))?; config.backup.validate()?; config.replication.validate()?; + config.self_update.validate()?; Ok(config) } } @@ -548,6 +608,41 @@ mod tests { assert!(matches!(Config::load(&path), Err(Error::Config(_)))); } + #[test] + fn self_update_section_defaults_to_disabled() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + std::fs::write(&path, DEV_DEFAULTS).unwrap(); + let cfg = Config::load(&path).unwrap(); + assert!(!cfg.self_update.enabled); + assert_eq!(cfg.self_update.branch, "main"); + assert_eq!(cfg.self_update.job, "build"); + assert_eq!(cfg.self_update.artifact, "dist_forge"); + } + + #[test] + fn self_update_enabled_requires_owner_name_repo() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + let base = format!("{DEV_DEFAULTS}\n[self_update]\nenabled = true\n"); + for repo in ["", "forge", "a/b/c", "/forge", "owner/"] { + std::fs::write(&path, format!("{base}repo = \"{repo}\"\n")).unwrap(); + assert!(Config::load(&path).is_err(), "repo `{repo}` should be refused"); + } + std::fs::write(&path, format!("{base}repo = \"Tahinli/forge\"\n")).unwrap(); + let cfg = Config::load(&path).unwrap(); + assert!(cfg.self_update.enabled); + assert_eq!(cfg.self_update.repo, "Tahinli/forge"); + } + + #[test] + fn self_update_rejects_unknown_keys() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("forge.toml"); + std::fs::write(&path, format!("{DEV_DEFAULTS}\n[self_update]\nbogus = 1\n")).unwrap(); + assert!(Config::load(&path).is_err()); + } + #[test] fn backup_section_is_parsed_and_validated() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/forge-core/src/lfs_token.rs b/crates/forge-core/src/lfs_token.rs index f392900..ff92cc9 100644 --- a/crates/forge-core/src/lfs_token.rs +++ b/crates/forge-core/src/lfs_token.rs @@ -1,4 +1,4 @@ -//! Short-lived signed tokens for Git LFS transfer actions (see docs/wave-b-interfaces.md). +//! Short-lived signed tokens for Git LFS transfer actions. //! //! Token format: `".."`, where the MAC covers //! `"lfs\0" + repo_id + "\0" + op + "\0" + expires`. `op` is `download`, `upload` or `any`. diff --git a/crates/forge-core/src/model.rs b/crates/forge-core/src/model.rs index aab35b3..b9eb52a 100644 --- a/crates/forge-core/src/model.rs +++ b/crates/forge-core/src/model.rs @@ -1,4 +1,4 @@ -//! Domain types. Stored shapes are described in docs/m1-interfaces.md. +//! Domain types. Stored shapes are described in docs/architecture.md, section 4. pub type Id = String; diff --git a/crates/forge-core/src/raw_token.rs b/crates/forge-core/src/raw_token.rs index 67a9ee8..66d5882 100644 --- a/crates/forge-core/src/raw_token.rs +++ b/crates/forge-core/src/raw_token.rs @@ -1,4 +1,4 @@ -//! Signed tokens for private raw-file URLs (see docs/m2-interfaces.md). +//! Signed tokens for private raw-file URLs. //! //! Token format: `"."`, where the MAC covers //! `"raw-v1:" + repo_id + ":" + expires`. diff --git a/crates/forge-git/src/browse.rs b/crates/forge-git/src/browse.rs index 32a02b1..80251b0 100644 --- a/crates/forge-git/src/browse.rs +++ b/crates/forge-git/src/browse.rs @@ -1,4 +1,4 @@ -//! In-process repo reads via gix (see docs/m2-interfaces.md). +//! In-process repo reads via gix. //! //! Everything here is blocking; callers run it inside `spawn_blocking`. Repositories are opened //! isolated: the environment and user/system git configuration are ignored. diff --git a/crates/forge-git/src/history.rs b/crates/forge-git/src/history.rs index 38011cd..06b1630 100644 --- a/crates/forge-git/src/history.rs +++ b/crates/forge-git/src/history.rs @@ -1,4 +1,4 @@ -//! git CLI history: log, commit diff, last commits, archive (see docs/m2-interfaces.md). +//! git CLI history: log, commit diff, last commits, archive. //! Every commit argument is a validated full hex OID; paths go after `--` as literal pathspecs. use std::collections::{HashMap, HashSet}; diff --git a/crates/forge-runner/src/cli.rs b/crates/forge-runner/src/cli.rs index fef2950..400f106 100644 --- a/crates/forge-runner/src/cli.rs +++ b/crates/forge-runner/src/cli.rs @@ -18,8 +18,9 @@ use crate::client::ForgeClient; use crate::config::{self, ExecutorKind, ImagesConfig, Limits, RunnerConfig, UsernsMode}; use crate::executor::{BuiltinExecutor, Executor, PodmanExecutor}; use crate::oci::ImageStore; -use crate::runner::{RunOptions, Runner}; +use crate::runner::{RunEnd, RunOptions, Runner}; use crate::sandbox::idmap::IdMap; +use crate::update; /// How often unused images are garbage collected, after the one at startup. const GC_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60); @@ -124,7 +125,7 @@ where }; runtime.block_on(async { match run(cli).await { - Ok(()) => ExitCode::SUCCESS, + Ok(code) => code, Err(e) => { eprintln!("{bin_name}: {e}"); ExitCode::FAILURE @@ -166,7 +167,7 @@ fn hidden_dispatch(args: &[OsString]) -> i32 { } } -async fn run(cli: Cli) -> Result<(), Box> { +async fn run(cli: Cli) -> Result> { match cli.command { Command::Register { url, @@ -205,6 +206,7 @@ async fn run(cli: Cli) -> Result<(), Box> { images: ImagesConfig::default(), sandbox: config::SandboxConfig::default(), registries: Vec::new(), + auto_update: true, }; config::save(&path, &cfg)?; println!( @@ -212,7 +214,7 @@ async fn run(cli: Cli) -> Result<(), Box> { resp.runner_id, path.display() ); - Ok(()) + Ok(ExitCode::SUCCESS) } Command::Run { config: path } => { let path = match path { @@ -255,8 +257,11 @@ async fn run(cli: Cli) -> Result<(), Box> { stop.cancel(); } }); - runner.run(shutdown).await; - Ok(()) + match runner.run(shutdown).await { + RunEnd::Stopped => Ok(ExitCode::SUCCESS), + // systemd restarts the runner on this code, and it starts the new binary. + RunEnd::Updated => Ok(ExitCode::from(update::RESTART_EXIT_CODE)), + } } Command::Check { work_dir, @@ -269,7 +274,7 @@ async fn run(cli: Cli) -> Result<(), Box> { let mode = check_userns_mode(config_path)?; let helper = std::env::current_exe()?; if crate::check::run(&helper, &work_dir, mode).await { - Ok(()) + Ok(ExitCode::SUCCESS) } else { Err("some host checks failed, see the report above".into()) } diff --git a/crates/forge-runner/src/client.rs b/crates/forge-runner/src/client.rs index 8ced865..70af693 100644 --- a/crates/forge-runner/src/client.rs +++ b/crates/forge-runner/src/client.rs @@ -11,16 +11,25 @@ use forge_ci::proto::{ RegisterResponse, }; use reqwest::StatusCode; -use reqwest::header::CONTENT_LENGTH; +use reqwest::header::{CONTENT_LENGTH, HeaderMap}; use serde::de::DeserializeOwned; +use sha2::{Digest, Sha256}; +use tokio::io::AsyncWriteExt; /// The claim long-poll is 25s on the forge side, so 35s leaves room for the response. pub const CLAIM_TIMEOUT: Duration = Duration::from_secs(35); const REQUEST_TIMEOUT: Duration = Duration::from_secs(60); const LOG_TIMEOUT: Duration = Duration::from_secs(60); const ARTIFACT_TIMEOUT: Duration = Duration::from_secs(60 * 60); +const BINARY_TIMEOUT: Duration = Duration::from_secs(10 * 60); const HEADER_LOG_OFFSET: &str = "X-Forge-Log-Offset"; const HEADER_LOG_SIZE: &str = "X-Forge-Log-Size"; +/// Sent on every claim: `-` of this runner, for example `x86_64-linux`. +const HEADER_RUNNER_TARGET: &str = "Forge-Runner-Target"; +/// On a claim response: the sha256 (hex) of the forge's own binary, if the forge advertises one. +const HEADER_BINARY_SHA256: &str = "Forge-Binary-Sha256"; +/// `GET`: the forge's binary, for a runner that is updating itself. +const BINARY_PATH: &str = "/api/v1/ci/runners/binary"; /// Errors from talking to the forge. #[derive(Debug, thiserror::Error)] @@ -44,6 +53,15 @@ pub enum LogAck { Resync(u64), } +/// The forge's answer to a claim. +#[derive(Clone, Debug)] +pub struct ClaimReply { + /// The job assigned to this runner, or `None` when there is nothing to run (204). + pub job: Option, + /// The sha256 (lowercase hex) of the forge's binary, when the response advertises one. + pub binary_sha256: Option, +} + /// A client for one forge base URL. #[derive(Clone, Debug)] pub struct ForgeClient { @@ -80,30 +98,67 @@ impl ForgeClient { json_or_error(resp).await } - /// `POST /api/v1/ci/runners/claim`. Returns `None` on 204 (nothing to run). + /// `POST /api/v1/ci/runners/claim`. A 204 means nothing to run, and the reply has no job. pub async fn claim( &self, runner_secret: &str, labels: &[String], - ) -> Result, ClientError> { + ) -> Result { let req = ClaimRequest { labels: labels.to_vec(), }; + let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS); let resp = self .http .post(self.url("/api/v1/ci/runners/claim")) .bearer_auth(runner_secret) + .header(HEADER_RUNNER_TARGET, target) .json(&req) .timeout(CLAIM_TIMEOUT) .send() .await?; + let binary_sha256 = advertised_sha256(resp.headers()); match resp.status() { - StatusCode::NO_CONTENT => Ok(None), - status if status.is_success() => Ok(Some(resp.json().await?)), + StatusCode::NO_CONTENT => Ok(ClaimReply { + job: None, + binary_sha256, + }), + status if status.is_success() => Ok(ClaimReply { + job: Some(resp.json().await?), + binary_sha256, + }), _ => Err(status_error(resp).await), } } + /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the + /// sha256 (lowercase hex) of the bytes written. The caller checks it against the advertised + /// value and syncs the file. + pub async fn download_binary( + &self, + runner_secret: &str, + dest: &Path, + ) -> Result { + let mut resp = self + .http + .get(self.url(BINARY_PATH)) + .bearer_auth(runner_secret) + .timeout(BINARY_TIMEOUT) + .send() + .await?; + if !resp.status().is_success() { + return Err(status_error(resp).await); + } + let mut file = tokio::fs::File::create(dest).await?; + let mut hasher = Sha256::new(); + while let Some(chunk) = resp.chunk().await? { + hasher.update(&chunk); + file.write_all(&chunk).await?; + } + file.flush().await?; + Ok(hex::encode(hasher.finalize())) + } + /// `POST /api/v1/ci/jobs/{id}/logs` with the byte offset of `body` in the job log. pub async fn post_logs( &self, @@ -205,6 +260,16 @@ impl ForgeClient { } } +/// The `Forge-Binary-Sha256` header, trimmed and lowercased. An empty value counts as absent. +fn advertised_sha256(headers: &HeaderMap) -> Option { + headers + .get(HEADER_BINARY_SHA256)? + .to_str() + .ok() + .map(|v| v.trim().to_ascii_lowercase()) + .filter(|v| !v.is_empty()) +} + async fn json_or_error(resp: reqwest::Response) -> Result { if resp.status().is_success() { Ok(resp.json().await?) diff --git a/crates/forge-runner/src/config.rs b/crates/forge-runner/src/config.rs index 2aeb599..4b4311c 100644 --- a/crates/forge-runner/src/config.rs +++ b/crates/forge-runner/src/config.rs @@ -130,12 +130,21 @@ pub struct RunnerConfig { pub sandbox: SandboxConfig, #[serde(default, rename = "registry")] pub registries: Vec, + /// When true (the default), an idle runner replaces itself with the forge's binary when the + /// forge advertises a different one on the claim response. The runner then exits with code + /// 75 and systemd restarts it. Set `auto_update = false` to pin the binary by hand. + #[serde(default = "default_auto_update")] + pub auto_update: bool, } fn default_concurrency() -> usize { 1 } +fn default_auto_update() -> bool { + true +} + fn default_keep_days() -> u32 { 7 } @@ -159,6 +168,7 @@ impl fmt::Debug for RunnerConfig { .field("executor", &self.executor) .field("images", &self.images) .field("registries", &self.registries) + .field("auto_update", &self.auto_update) .finish() } } @@ -268,6 +278,7 @@ mod tests { images: ImagesConfig::default(), sandbox: SandboxConfig::default(), registries: Vec::new(), + auto_update: true, } } @@ -340,6 +351,20 @@ mod tests { assert_eq!(config.images.keep_days, 7); assert_eq!(config.limits.image_max_gb, 20); assert!(config.registries.is_empty()); + assert!(config.auto_update); + } + + #[test] + fn auto_update_can_be_turned_off() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("runner.toml"); + std::fs::write( + &path, + "url = \"https://f\"\nrunner_id = \"r\"\nrunner_secret = \"s\"\nname = \"n\"\n\ + work_dir = \"/w\"\nauto_update = false\n", + ) + .expect("write"); + assert!(!load(&path).expect("load").auto_update); } #[test] diff --git a/crates/forge-runner/src/executor.rs b/crates/forge-runner/src/executor.rs index 8eff623..008367b 100644 --- a/crates/forge-runner/src/executor.rs +++ b/crates/forge-runner/src/executor.rs @@ -519,7 +519,7 @@ impl ImageSource for ImageStore { } /// Runs jobs in a libcontainer sandbox, started as `helper` (`forge-runner __sandbox`). It needs -/// no external container tool. See `docs/ci-builtin-executor.md`. +/// no external container tool. See `docs/ci.md`. pub struct BuiltinExecutor { images: I, limits: Limits, diff --git a/crates/forge-runner/src/lib.rs b/crates/forge-runner/src/lib.rs index 16fe75c..09dce82 100644 --- a/crates/forge-runner/src/lib.rs +++ b/crates/forge-runner/src/lib.rs @@ -14,4 +14,5 @@ pub mod logs; pub mod oci; pub mod runner; pub mod sandbox; +pub mod update; pub mod workspace; diff --git a/crates/forge-runner/src/runner.rs b/crates/forge-runner/src/runner.rs index 106cd44..1e0fcf2 100644 --- a/crates/forge-runner/src/runner.rs +++ b/crates/forge-runner/src/runner.rs @@ -16,6 +16,7 @@ use crate::client::{ClientError, ForgeClient}; use crate::config::RunnerConfig; use crate::executor::{ExecRequest, ExecResult, Executor}; use crate::logs::{self, PumpConfig}; +use crate::update::{self, Installed, UpdateState}; use crate::workspace; /// Log lines queued between the executor and the log shipper. @@ -46,6 +47,15 @@ impl Default for RunOptions { } } +/// How [`Runner::run`] ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RunEnd { + /// Shutdown was requested. + Stopped, + /// The binary was replaced. The caller exits with [`update::RESTART_EXIT_CODE`]. + Updated, +} + /// A runner bound to one forge and one executor. #[derive(Clone)] pub struct Runner { @@ -76,50 +86,114 @@ impl Runner { /// Claims and runs jobs, up to `concurrency` at a time, until `shutdown` is cancelled. Jobs /// still running at shutdown are cancelled and reported as cancelled. - pub async fn run(&self, shutdown: CancellationToken) { + /// + /// When the forge advertises a different binary and `auto_update` is on, no new jobs are + /// claimed. Once the running jobs finish, the binary is replaced and the loop returns + /// [`RunEnd::Updated`]. + pub async fn run(&self, shutdown: CancellationToken) -> RunEnd { let semaphore = Arc::new(Semaphore::new(self.config.concurrency)); let mut jobs: JoinSet<()> = JoinSet::new(); + // Hashed once at startup. Without it, or with auto_update off, updates stay disabled. + let exe = if self.config.auto_update { + match update::locate_self() { + Ok(found) => Some(found), + Err(e) => { + tracing::warn!(error = %e, "auto update disabled, cannot read own binary"); + None + } + } + } else { + None + }; + let mut updates = UpdateState::new( + self.config.auto_update, + exe.as_ref().map(|(_, sha)| sha.clone()), + ); tracing::info!( name = %self.config.name, concurrency = self.config.concurrency, + auto_update = updates.enabled(), "runner started" ); - loop { + let end = loop { + if let Some((exe_path, _)) = &exe + && let Some(sha) = updates.pending().map(str::to_owned) + { + if !jobs.is_empty() { + // Claiming is paused until the running jobs finish. + tokio::select! { + _ = shutdown.cancelled() => break RunEnd::Stopped, + Some(joined) = jobs.join_next() => { + if let Err(e) = joined { + tracing::error!(error = %e, "job task panicked"); + } + } + } + continue; + } + match update::install(&self.client, &self.config.runner_secret, exe_path, &sha) + .await + { + Ok(Installed::Replaced) => { + tracing::info!(sha = %sha, "binary updated, restarting"); + break RunEnd::Updated; + } + Ok(Installed::Listed) => { + tracing::warn!(sha = %sha, "forge binary is on the bad list, not updating"); + updates.give_up(&sha); + } + Err(e) => { + tracing::warn!(sha = %sha, error = %e, "update failed, keeping this binary"); + updates.give_up(&sha); + } + } + continue; + } + let permit = tokio::select! { - _ = shutdown.cancelled() => break, + _ = shutdown.cancelled() => break RunEnd::Stopped, permit = semaphore.clone().acquire_owned() => match permit { Ok(permit) => permit, - Err(_) => break, + Err(_) => break RunEnd::Stopped, }, }; let claimed = tokio::select! { _ = shutdown.cancelled() => { drop(permit); - break; + break RunEnd::Stopped; } r = self.client.claim(&self.config.runner_secret, &self.config.labels) => r, }; match claimed { - Ok(Some(job)) => { - tracing::info!( - job_id = %job.job_id, - job_name = %job.job_name, - repo = %job.repo, - "claimed job" - ); - let runner = self.clone(); - let cancel = shutdown.child_token(); - jobs.spawn(async move { - let _permit = permit; - runner.process(job, cancel).await; - }); + Ok(reply) => { + if updates.observe(reply.binary_sha256.as_deref()) + && let Some(sha) = updates.pending() + { + tracing::info!(sha = %sha, "forge advertises a new binary, updating when idle"); + } + match reply.job { + Some(job) => { + tracing::info!( + job_id = %job.job_id, + job_name = %job.job_name, + repo = %job.repo, + "claimed job" + ); + let runner = self.clone(); + let cancel = shutdown.child_token(); + jobs.spawn(async move { + let _permit = permit; + runner.process(job, cancel).await; + }); + } + None => drop(permit), + } } - Ok(None) => drop(permit), Err(e) => { drop(permit); tracing::warn!(error = %e, "claim failed, backing off"); tokio::select! { - _ = shutdown.cancelled() => break, + _ = shutdown.cancelled() => break RunEnd::Stopped, _ = tokio::time::sleep(self.options.claim_backoff) => {} } } @@ -129,13 +203,14 @@ impl Runner { tracing::error!(error = %e, "job task panicked"); } } - } + }; while let Some(joined) = jobs.join_next().await { if let Err(e) = joined { tracing::error!(error = %e, "job task panicked"); } } tracing::info!("runner stopped"); + end } /// Runs one claimed job end to end and reports its result. Returns the final outcome. diff --git a/crates/forge-runner/src/sandbox/mod.rs b/crates/forge-runner/src/sandbox/mod.rs index 65d89f2..1878d23 100644 --- a/crates/forge-runner/src/sandbox/mod.rs +++ b/crates/forge-runner/src/sandbox/mod.rs @@ -3,7 +3,7 @@ //! The runner never calls libcontainer itself. libcontainer forks and clones, which is unsafe in //! a multi-threaded tokio process, so the runner spawns `forge-runner __sandbox` as a //! single-threaded child. That child reads a [`SandboxRequest`] on stdin and runs the job. See -//! `docs/ci-builtin-executor.md`. +//! `docs/ci.md`. pub mod exec; pub mod helper; diff --git a/crates/forge-runner/src/update.rs b/crates/forge-runner/src/update.rs new file mode 100644 index 0000000..1b7198e --- /dev/null +++ b/crates/forge-runner/src/update.rs @@ -0,0 +1,330 @@ +//! Self-update for an idle runner. Each claim response may advertise the sha256 of the forge's +//! binary. When that differs from ours, the runner stops claiming, lets its running jobs finish, +//! swaps its own binary for the forge's, and exits with [`RESTART_EXIT_CODE`] so systemd starts +//! the new one. +//! +//! [`UpdateState`] makes the decisions and does no I/O. [`install`] does the file work. + +use std::io::Read; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::time::Duration; + +use sha2::{Digest, Sha256}; + +use crate::client::{ClientError, ForgeClient}; + +/// The exit code after a successful swap. systemd restarts the runner on any non-zero code. +pub const RESTART_EXIT_CODE: u8 = 75; +/// How long the new binary gets to answer `--version`. +const SMOKE_TIMEOUT: Duration = Duration::from_secs(10); +/// The temp file, next to the running binary, that the download goes to. +const NEW_NAME: &str = ".forge-runner.new"; +/// The previous binary, kept for a manual rollback. +const PREV_SUFFIX: &str = ".prev"; +/// Optional list of bad binaries, one sha256 per line, next to the running binary. +const BAD_SUFFIX: &str = ".bad"; + +/// Decides whether an update is due. It remembers the last sha that failed, so the runner does +/// not retry it on every claim. A different advertised sha clears that memory. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UpdateState { + enabled: bool, + /// The sha256 of the running binary. Updates are disabled when it is unknown. + current: Option, + pending: Option, + given_up: Option, +} + +impl UpdateState { + /// `current` is the sha256 (lowercase hex) of the running binary. + pub fn new(auto_update: bool, current: Option) -> Self { + Self { + enabled: auto_update && current.is_some(), + current, + pending: None, + given_up: None, + } + } + + /// Records the sha the forge advertised on a claim response. Returns true when this makes a + /// new update due. An absent header changes nothing. + pub fn observe(&mut self, advertised: Option<&str>) -> bool { + if !self.enabled { + return false; + } + let Some(advertised) = advertised else { + return false; + }; + if Some(advertised) == self.current.as_deref() + || Some(advertised) == self.given_up.as_deref() + { + // Already running it, or it failed and the forge has not moved on. + self.pending = None; + return false; + } + if self.pending.as_deref() == Some(advertised) { + return false; + } + self.pending = Some(advertised.to_owned()); + true + } + + /// Whether updates are on at all. False when `auto_update` is off or the binary is unknown. + pub fn enabled(&self) -> bool { + self.enabled + } + + /// The sha to update to, if an update is due. + pub fn pending(&self) -> Option<&str> { + self.pending.as_deref() + } + + /// Stops trying `sha` until the forge advertises a different one. + pub fn give_up(&mut self, sha: &str) { + self.given_up = Some(sha.to_owned()); + self.pending = None; + } +} + +/// Whether a `.bad` list, one sha256 per line, names `sha`. +pub fn is_listed_bad(list: &str, sha: &str) -> bool { + list.lines() + .any(|line| line.trim().eq_ignore_ascii_case(sha)) +} + +/// The sha256 (lowercase hex) of the file at `path`. +pub fn file_sha256(path: &Path) -> std::io::Result { + let mut file = std::fs::File::open(path)?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 64 * 1024]; + loop { + let n = file.read(&mut buf)?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + } + Ok(hex::encode(hasher.finalize())) +} + +/// The path of the running binary, and the sha256 of its contents. +pub fn locate_self() -> std::io::Result<(PathBuf, String)> { + let exe = std::env::current_exe()?; + let sha = file_sha256(&exe)?; + Ok((exe, sha)) +} + +/// What [`install`] did when it did not fail. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Installed { + /// The new binary is in place. The caller should exit with [`RESTART_EXIT_CODE`]. + Replaced, + /// The `.bad` list names the advertised binary, so nothing was replaced. + Listed, +} + +/// Why an update failed. The current binary is untouched in every case. +#[derive(Debug, thiserror::Error)] +pub enum UpdateError { + #[error("local io: {0}")] + Io(#[from] std::io::Error), + #[error("download: {0}")] + Download(#[from] ClientError), + #[error("sha256 mismatch: forge advertised {expected}, downloaded {actual}")] + Mismatch { expected: String, actual: String }, + #[error("new binary failed its check: {0}")] + Smoke(String), +} + +/// Downloads the forge's binary next to `exe`, checks it, and swaps it in. The old binary is kept +/// as `.prev`. On any error the temp file is removed. +pub async fn install( + client: &ForgeClient, + runner_secret: &str, + exe: &Path, + expected: &str, +) -> Result { + let new = exe.with_file_name(NEW_NAME); + // A temp file left by an earlier crash must not be reused. + let _ = std::fs::remove_file(&new); + let result = stage_and_swap(client, runner_secret, exe, &new, expected).await; + if !matches!(result, Ok(Installed::Replaced)) { + let _ = std::fs::remove_file(&new); + } + result +} + +async fn stage_and_swap( + client: &ForgeClient, + runner_secret: &str, + exe: &Path, + new: &Path, + expected: &str, +) -> Result { + let actual = client.download_binary(runner_secret, new).await?; + if actual != expected { + return Err(UpdateError::Mismatch { + expected: expected.to_owned(), + actual, + }); + } + std::fs::set_permissions(new, std::fs::Permissions::from_mode(0o755))?; + std::fs::File::open(new)?.sync_all()?; + smoke_test(new).await?; + + let bad = match std::fs::read_to_string(sibling(exe, BAD_SUFFIX)) { + Ok(list) => list, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(), + Err(e) => return Err(e.into()), + }; + if is_listed_bad(&bad, expected) { + return Ok(Installed::Listed); + } + + let prev = sibling(exe, PREV_SUFFIX); + match std::fs::remove_file(&prev) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e.into()), + } + // A hard link keeps the old inode alive at no cost. Copy only where links are not allowed. + if std::fs::hard_link(exe, &prev).is_err() { + std::fs::copy(exe, &prev)?; + } + std::fs::rename(new, exe)?; + Ok(Installed::Replaced) +} + +/// Runs ` --version` and requires exit 0 within [`SMOKE_TIMEOUT`]. +async fn smoke_test(bin: &Path) -> Result<(), UpdateError> { + let output = tokio::time::timeout( + SMOKE_TIMEOUT, + tokio::process::Command::new(bin) + .arg("--version") + .stdin(Stdio::null()) + .kill_on_drop(true) + .output(), + ) + .await + .map_err(|_| UpdateError::Smoke("--version did not finish in time".into()))??; + if !output.status.success() { + return Err(UpdateError::Smoke(format!( + "--version exited with {}", + output.status + ))); + } + Ok(()) +} + +/// `exe` with `suffix` appended to its file name, for example `forge.prev`. +fn sibling(exe: &Path, suffix: &str) -> PathBuf { + let mut name = exe.as_os_str().to_owned(); + name.push(suffix); + PathBuf::from(name) +} + +#[cfg(test)] +mod tests { + use super::*; + + const OURS: &str = "aaaa"; + const THEIRS: &str = "bbbb"; + + fn state(auto_update: bool) -> UpdateState { + UpdateState::new(auto_update, Some(OURS.to_owned())) + } + + #[test] + fn a_different_sha_becomes_pending_once() { + let mut s = state(true); + assert!(s.observe(Some(THEIRS))); + assert_eq!(s.pending(), Some(THEIRS)); + // The same sha again is not news. + assert!(!s.observe(Some(THEIRS))); + assert_eq!(s.pending(), Some(THEIRS)); + } + + #[test] + fn matching_sha_or_no_header_leaves_nothing_pending() { + let mut s = state(true); + assert!(!s.observe(Some(OURS))); + assert_eq!(s.pending(), None); + assert!(!s.observe(None)); + assert_eq!(s.pending(), None); + } + + #[test] + fn absent_header_keeps_a_pending_update() { + let mut s = state(true); + s.observe(Some(THEIRS)); + s.observe(None); + assert_eq!(s.pending(), Some(THEIRS)); + } + + #[test] + fn disabled_or_unknown_current_never_pends() { + let mut off = state(false); + assert!(!off.observe(Some(THEIRS))); + assert_eq!(off.pending(), None); + + let mut unknown = UpdateState::new(true, None); + assert!(!unknown.observe(Some(THEIRS))); + assert_eq!(unknown.pending(), None); + } + + #[test] + fn a_failed_sha_is_not_retried_until_the_forge_moves_on() { + let mut s = state(true); + s.observe(Some(THEIRS)); + s.give_up(THEIRS); + assert_eq!(s.pending(), None); + + // Claims keep advertising the same sha: nothing becomes pending. + assert!(!s.observe(Some(THEIRS))); + assert_eq!(s.pending(), None); + + // A different sha is due again. + assert!(s.observe(Some("cccc"))); + assert_eq!(s.pending(), Some("cccc")); + } + + #[test] + fn going_back_to_the_failed_sha_cancels_a_pending_update() { + let mut s = state(true); + s.observe(Some(THEIRS)); + s.give_up(THEIRS); + s.observe(Some("cccc")); + s.observe(Some(THEIRS)); + assert_eq!(s.pending(), None); + } + + #[test] + fn bad_list_matches_whole_lines_case_insensitively() { + let list = "# comment is not a sha\nBBBB\n cccc \n"; + assert!(is_listed_bad(list, THEIRS)); + assert!(is_listed_bad(list, "cccc")); + assert!(!is_listed_bad(list, "bbb")); + assert!(!is_listed_bad("", THEIRS)); + } + + #[test] + fn sibling_appends_the_suffix() { + assert_eq!( + sibling(Path::new("/home/t/.local/bin/forge"), PREV_SUFFIX), + PathBuf::from("/home/t/.local/bin/forge.prev") + ); + } + + #[test] + fn file_sha256_matches_a_known_digest() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("f"); + std::fs::write(&path, b"abc").expect("write"); + assert_eq!( + file_sha256(&path).expect("hash"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + } +} diff --git a/crates/forge-runner/tests/flow.rs b/crates/forge-runner/tests/flow.rs index 2ed7360..fac0611 100644 --- a/crates/forge-runner/tests/flow.rs +++ b/crates/forge-runner/tests/flow.rs @@ -16,7 +16,7 @@ use forge_ci::proto::{FinishRequest, JobAssignment, Outcome, RegisterResponse}; use forge_runner::config::{Limits, RunnerConfig}; use forge_runner::executor::HostExecutor; use forge_runner::logs::PumpConfig; -use forge_runner::runner::{RunOptions, Runner}; +use forge_runner::runner::{RunEnd, RunOptions, Runner}; use http_body_util::{BodyExt, Full}; use hyper::body::Incoming; use hyper::header::{AUTHORIZATION, HeaderMap}; @@ -321,6 +321,7 @@ fn config(url: &str, work_dir: PathBuf) -> RunnerConfig { images: forge_runner::config::ImagesConfig::default(), sandbox: forge_runner::config::SandboxConfig::default(), registries: Vec::new(), + auto_update: true, } } @@ -349,7 +350,7 @@ async fn wait_until(what: &str, mut check: impl FnMut() -> bool) { struct Harness { state: Shared, stop: CancellationToken, - runner_task: tokio::task::JoinHandle<()>, + runner_task: tokio::task::JoinHandle, _dir: tempfile::TempDir, } diff --git a/crates/forge-web/src/backup/mod.rs b/crates/forge-web/src/backup/mod.rs index 6dd374c..6cce490 100644 --- a/crates/forge-web/src/backup/mod.rs +++ b/crates/forge-web/src/backup/mod.rs @@ -1,4 +1,4 @@ -//! Backup sets (phase 1, see `docs/backup-interfaces.md`). +//! Backup sets (phase 1, see `docs/backup.md`). //! //! A set is a directory `forge-backup-/` holding a consistent DB snapshot, one git //! bundle per non-empty repo, optionally the instance key, and a `manifest.json` with a sha256 for diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 3b83fa6..09b2430 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -55,6 +55,13 @@ pub async fn serve(config: Config) -> forge_core::Result<()> { let forge_bin = std::env::current_exe()?.canonicalize()?; forge_git::setup::write_hook_shims(&data_dir, &forge_bin)?; + // Hash the running binary once, before any runner can ask for it. Hashing reads the whole + // executable, which takes tens of seconds for a debug build, so it runs off the boot path and + // the listeners bind first. Any caller that needs the hash waits on the same `OnceLock`. + tokio::task::spawn_blocking(|| { + crate::self_update::running(); + }); + let internal_token: Arc = Arc::from(random_hex()); let admin_token: Arc = Arc::from(random_hex()); crate::admin_client::write_admin_token(&data_dir, &admin_token)?; @@ -99,6 +106,8 @@ pub async fn serve(config: Config) -> forge_core::Result<()> { ci_waker: Arc::new(Notify::new()), mailer, mail_waker: Arc::new(Notify::new()), + notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()), + ci_live: Arc::new(crate::ci::CiLive::default()), }; if let Err(e) = crate::signatures::rebuild_allowed_signers(&state).await { tracing::error!(error = %e, "building the SSH allowed-signers file failed"); @@ -150,6 +159,14 @@ pub async fn serve(config: Config) -> forge_core::Result<()> { let (stop_tx, stop_rx) = watch::channel(false); + // Open notification streams never end on their own, so they are closed with the rest. + let hub = Arc::clone(&state.notify_hub); + let hub_stop = stop_rx.clone(); + tokio::spawn(async move { + wait_stop(hub_stop).await; + hub.close(); + }); + let ssh_config = SshConfig { listen: ssh_listen, host_key_path: data_dir.join("ssh_host_ed25519_key"), @@ -169,8 +186,10 @@ pub async fn serve(config: Config) -> forge_core::Result<()> { let signal_stop = stop_tx.clone(); tokio::spawn(async move { - shutdown_signal().await; - tracing::info!("shutdown signal received"); + tokio::select! { + () = shutdown_signal() => tracing::info!("shutdown signal received"), + () = crate::self_update::restart_requested() => tracing::info!("self-update: restarting"), + } signal_stop.send_replace(true); }); diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index fb15704..6b35cfc 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -1,4 +1,4 @@ -//! Runner and job API under `/api/v1/ci` (contract: docs/ci-interfaces.md, section 4). +//! Runner and job API under `/api/v1/ci` (see docs/ci.md, Runner protocol). //! //! Runners authenticate with `Authorization: Bearer `. A job's routes take //! `Authorization: Bearer `, which `job_by_token` accepts only while the job is Running. @@ -25,6 +25,7 @@ use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route}; use crate::api::{self, Refusal}; use crate::ci::{artifact_key, log_path}; use crate::pages::repo::https_clone_url; +use crate::self_update; use crate::state::AppState; path_param!(job_id); @@ -170,6 +171,13 @@ async fn register(cx: &Cx, body: Body) -> topcoat::Result { #[route(POST "/api/v1/ci/runners/claim")] async fn claim(cx: &Cx) -> topcoat::Result { + let mut res = claim_work(cx).await?; + // Advertises the binary sha256 when self-update is on and the runner asked for this target. + self_update::advertise(app_context::(cx), headers(cx), &mut res); + Ok(res) +} + +async fn claim_work(cx: &Cx) -> topcoat::Result { let state = app_context::(cx); // The labels in the request are ignored: the labels stored at registration are used. let runner = match runner_from(state, headers(cx)).await { @@ -177,24 +185,48 @@ async fn claim(cx: &Cx) -> topcoat::Result { Err(res) => return Ok(*res), }; - // Register for the wake-up before the first attempt, so a job queued in between is not missed. + // Arm the wake-up before each attempt, so a job queued during the attempt is not missed. + // Producers use notify_waiters, which wakes every claimer, so a runner whose labels + // don't match a job re-arms and keeps waiting for the rest of CLAIM_WAIT. let waker = state.ci_waker.clone(); - let mut woken = std::pin::pin!(waker.notified()); - woken.as_mut().enable(); + let deadline = tokio::time::Instant::now() + CLAIM_WAIT; + loop { + let mut woken = std::pin::pin!(waker.notified()); + woken.as_mut().enable(); + + match try_claim(state, &runner).await { + Ok(Some(assignment)) => return Ok(assignment_response(&assignment)), + Ok(None) => {} + Err(res) => return Ok(*res), + } + if tokio::time::timeout_at(deadline, woken.as_mut()) + .await + .is_err() + { + return Ok(empty(StatusCode::NO_CONTENT)); + } + } +} - match try_claim(state, &runner).await { - Ok(Some(assignment)) => return Ok(assignment_response(&assignment)), - Ok(None) => {} - Err(res) => return Ok(*res), +/// The running binary, for a runner that updates itself. 404 unless self-update is enabled. +#[route(GET "/api/v1/ci/runners/binary")] +async fn runner_binary(cx: &Cx) -> topcoat::Result { + let state = app_context::(cx); + if let Err(res) = runner_from(state, headers(cx)).await { + return Ok(*res); } - tokio::select! { - _ = woken.as_mut() => {} - _ = tokio::time::sleep(CLAIM_WAIT) => {} + if !state.config.self_update.enabled { + return Ok(api::error(StatusCode::NOT_FOUND, "self-update is disabled")); } - match try_claim(state, &runner).await { - Ok(Some(assignment)) => Ok(assignment_response(&assignment)), - Ok(None) => Ok(empty(StatusCode::NO_CONTENT)), - Err(res) => Ok(*res), + match self_update::binary_response().await { + Ok(res) => Ok(res), + Err(e) => { + tracing::error!(error = %e, "ci: serving the runner binary failed"); + Ok(api::error( + StatusCode::INTERNAL_SERVER_ERROR, + "the binary is unavailable", + )) + } } } @@ -217,6 +249,8 @@ async fn try_claim(state: &AppState, runner: &CiRunner) -> Result topcoat::Result { } /// Finishes the job, then syncs the statuses of the job and of every job whose state changed -/// (skipped or queued by this finish). Wakes the claimers when something was queued. +/// (skipped or queued by this finish). Wakes the claimers when something was queued, and the +/// watchers of every job and run that changed. async fn finish_job( state: &AppState, job: &CiJob, @@ -614,6 +650,7 @@ async fn finish_job( .map_err(api::internal)?; let mut queued = false; + let mut any_changed = false; for other in state .store .jobs_for_run(&job.run_id) @@ -621,6 +658,14 @@ async fn finish_job( .map_err(api::internal)? { let changed = before.get(&other.id) != Some(&other.state); + if changed { + any_changed = true; + if other.state.is_terminal() { + state.ci_live.close_job(&other.id); + } else { + state.ci_live.bump_job(&other.id); + } + } if other.id == job.id || (changed && matches!(other.state, JobState::Skipped | JobState::Queued)) { @@ -628,9 +673,14 @@ async fn finish_job( crate::ci::sync_status(state, &run, &other).await; } } + if any_changed { + state.ci_live.bump_run(&run.id); + } if queued { state.ci_waker.notify_waiters(); } + // A run that just went green may deploy the forge itself. + self_update::maybe_deploy(state, &run).await; Ok(run.state.as_str()) } diff --git a/crates/forge-web/src/ci/api_tests.rs b/crates/forge-web/src/ci/api_tests.rs index b766983..cfac0b8 100644 --- a/crates/forge-web/src/ci/api_tests.rs +++ b/crates/forge-web/src/ci/api_tests.rs @@ -769,3 +769,133 @@ async fn job_token_reads_over_smart_http_but_never_pushes() { "a finished job's token must stop working" ); } + +/// Like `bare`, with self-update enabled for `OWNER/REPO`. +async fn bare_with_self_update() -> Bare { + let dir = tempfile::tempdir().expect("tempdir"); + let data_dir = dir.path().to_path_buf(); + let mut state = test_state(&data_dir).await; + let mut config = (*state.config).clone(); + config.self_update.enabled = true; + config.self_update.repo = format!("{OWNER}/{REPO}"); + state.config = Arc::new(config); + let store = state.store.clone(); + let router = app_router(state); + let owner = store + .create_user(OWNER, None, "not-a-real-hash", false) + .await + .unwrap(); + let repo = store + .create_repo(&owner.id, REPO, "", Visibility::Public, "main") + .await + .unwrap(); + Bare { + router, + store, + data_dir, + owner_id: owner.id, + repo, + _dir: dir, + } +} + +#[tokio::test] +async fn runner_binary_needs_runner_auth_and_self_update() { + let env = bare(|_| {}).await; + let (_, secret) = runner(&env, &[]).await; + let uri = "/api/v1/ci/runners/binary"; + + let sent = send(&env.router, "GET", uri, &[], Vec::new()).await; + assert_eq!(sent.status, 401); + // Self-update is off in this fixture, so an authorized runner gets 404. + let sent = send(&env.router, "GET", uri, &[bearer(&secret)], Vec::new()).await; + assert_eq!(sent.status, 404); +} + +#[tokio::test] +async fn runner_binary_streams_the_running_binary_with_its_sha() { + use sha2::{Digest, Sha256}; + + let env = bare_with_self_update().await; + let (_, secret) = runner(&env, &[]).await; + let uri = "/api/v1/ci/runners/binary"; + + let sent = send( + &env.router, + "GET", + uri, + &[bearer("not-a-secret")], + Vec::new(), + ) + .await; + assert_eq!(sent.status, 401); + + let sent = send(&env.router, "GET", uri, &[bearer(&secret)], Vec::new()).await; + assert_eq!(sent.status, 200); + assert_eq!( + sent.headers.get(http::header::CONTENT_TYPE).unwrap(), + "application/octet-stream" + ); + let advertised = sent + .headers + .get("forge-binary-sha256") + .unwrap() + .to_str() + .unwrap(); + let digest = hex::encode(Sha256::digest(&sent.body)); + assert_eq!(digest, advertised); + assert_eq!( + advertised, + crate::self_update::running() + .expect("hashed at startup") + .sha256 + ); +} + +#[tokio::test] +async fn claim_advertises_the_binary_only_to_a_matching_target() { + let env = bare_with_self_update().await; + let (_, secret) = runner(&env, &["linux"]).await; + let target = crate::self_update::target(); + let claim_with = |target: Option| { + let mut headers = vec![bearer(&secret)]; + if let Some(target) = target { + headers.push(("Forge-Runner-Target", target)); + } + headers + }; + + // A 204 (no work) carries the header for a matching target. + let sent = send( + &env.router, + "POST", + "/api/v1/ci/runners/claim", + &claim_with(Some(target.clone())), + Vec::new(), + ) + .await; + assert_eq!(sent.status, 204); + let running = crate::self_update::running().expect("hashed at startup"); + assert_eq!( + sent.headers + .get("forge-binary-sha256") + .unwrap() + .to_str() + .unwrap(), + running.sha256 + ); + + // No target, or another target: no header. + for requested in [None, Some("riscv64-plan9".to_owned())] { + let sent = send( + &env.router, + "POST", + "/api/v1/ci/runners/claim", + &claim_with(requested), + Vec::new(), + ) + .await; + assert_eq!(sent.status, 204); + assert!(sent.headers.get("forge-binary-sha256").is_none()); + } +} diff --git a/crates/forge-web/src/ci/mod.rs b/crates/forge-web/src/ci/mod.rs index 0da27e4..4db9970 100644 --- a/crates/forge-web/src/ci/mod.rs +++ b/crates/forge-web/src/ci/mod.rs @@ -11,9 +11,11 @@ use forge_core::store::commit_status::StatusState; use crate::state::AppState; pub mod api; +pub mod live; pub mod reaper; pub mod schedule; +pub use live::CiLive; pub use schedule::{manual_run, on_pull_event, on_ref_update}; /// Longest status description written, in characters. Longer text is cut. diff --git a/crates/forge-web/src/lfs/mod.rs b/crates/forge-web/src/lfs/mod.rs index ba1b82e..4edb301 100644 --- a/crates/forge-web/src/lfs/mod.rs +++ b/crates/forge-web/src/lfs/mod.rs @@ -1,5 +1,4 @@ -//! Git LFS over HTTP: the batch API, object GET and PUT, and verify. See -//! `docs/wave-b-interfaces.md`, section 2. +//! Git LFS over HTTP: the batch API, object GET and PUT, and verify. //! //! Objects are content-addressed under `/lfs///` and shared by //! every repo. The `lfs_objects` table says which repo may use which object. Uploads stream into diff --git a/crates/forge-web/src/main.rs b/crates/forge-web/src/main.rs index ecd2f81..c5fa7fe 100644 --- a/crates/forge-web/src/main.rs +++ b/crates/forge-web/src/main.rs @@ -29,12 +29,14 @@ mod lfs_pointer; mod mail; mod mirrors; mod notify; +mod notify_hub; mod pages; mod post_update; mod pulls_sync; mod raw; mod render; mod replication; +mod self_update; mod signatures; mod ssh_backend; mod state; @@ -137,6 +139,14 @@ async fn real_main() -> ExitCode { let outcome: Result<(), BoxError> = match parts.as_slice() { [] | ["serve"] => serve(&config_path).await, + ["--version"] => { + println!( + "forge {} {}", + env!("CARGO_PKG_VERSION"), + env!("FORGE_BUILD_SHA") + ); + return ExitCode::SUCCESS; + } ["hook", stage] => hook_cmd::run(stage).await.map_err(Into::into), ["admin", "create-user", username] => admin_cli::create_user(&config_path, username, admin) .await @@ -209,6 +219,8 @@ async fn real_main() -> ExitCode { }; match outcome { + // A self-update swap asks for a restart. systemd Restart=on-failure starts the new binary. + Ok(()) if self_update::restart_pending() => ExitCode::from(self_update::RESTART_EXIT_CODE), Ok(()) => ExitCode::SUCCESS, Err(e) => { eprintln!("forge: {e}"); diff --git a/crates/forge-web/src/pages/archive.rs b/crates/forge-web/src/pages/archive.rs index 9663765..39dadca 100644 --- a/crates/forge-web/src/pages/archive.rs +++ b/crates/forge-web/src/pages/archive.rs @@ -1,5 +1,5 @@ //! Page: source archive at `/{owner}/{repo}/archive/{ref}.tar.gz` or `.zip`. The `git archive` -//! stdout is streamed as the response body (see docs/m2-interfaces.md). +//! stdout is streamed as the response body. use std::process::Stdio; diff --git a/crates/forge-web/src/pages/media.rs b/crates/forge-web/src/pages/media.rs index d4b4c57..682568c 100644 --- a/crates/forge-web/src/pages/media.rs +++ b/crates/forge-web/src/pages/media.rs @@ -2,7 +2,6 @@ //! from raw paths, since no ref name may start with `-`. It reads the Git LFS pointer at //! `ref:path` and streams the object it names, when the repo links that object. Access follows //! the raw route in `raw.rs`: public repos are open, and private repos need a signed `?token=`. -//! See `docs/wave-b-interfaces.md`, section 2. use forge_core::raw_token::verify_raw; use forge_core::{Repo, Visibility}; diff --git a/crates/forge-web/src/pages/settings_security.rs b/crates/forge-web/src/pages/settings_security.rs index 5e3d043..40da2e6 100644 --- a/crates/forge-web/src/pages/settings_security.rs +++ b/crates/forge-web/src/pages/settings_security.rs @@ -815,6 +815,7 @@ mod tests { advisories: Default::default(), mail: Default::default(), orgs: Default::default(), + self_update: Default::default(), }; let state = AppState { config: Arc::new(config), @@ -836,6 +837,8 @@ mod tests { ci_waker: Arc::new(tokio::sync::Notify::new()), mailer: Arc::new(crate::mail::FakeMailer::default()), mail_waker: Arc::new(tokio::sync::Notify::new()), + notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()), + ci_live: Arc::new(crate::ci::CiLive::default()), }; let hash = hash_password_async(PASSWORD.into()).await.unwrap(); let user = store diff --git a/crates/forge-web/src/raw.rs b/crates/forge-web/src/raw.rs index 1464616..58bef42 100644 --- a/crates/forge-web/src/raw.rs +++ b/crates/forge-web/src/raw.rs @@ -1,5 +1,5 @@ //! Raw user-content origin (separate listener, explicit routes; never `.discover()`). -//! See docs/m2-interfaces.md, "Raw origin". +//! See docs/architecture.md, section 5.5. use std::path::Path; use std::process::Stdio; diff --git a/crates/forge-web/src/render/highlight.rs b/crates/forge-web/src/render/highlight.rs index 17a7f09..0c9d518 100644 --- a/crates/forge-web/src/render/highlight.rs +++ b/crates/forge-web/src/render/highlight.rs @@ -1,4 +1,4 @@ -//! syntect class-based highlighting (see docs/m2-interfaces.md). +//! syntect class-based highlighting. //! //! Output is class-based (`hl-` prefix) and never carries inline styles, so the //! CSP without 'unsafe-inline' is respected. Each source line becomes one HTML diff --git a/crates/forge-web/src/render/markdown.rs b/crates/forge-web/src/render/markdown.rs index a8ab480..5fd5444 100644 --- a/crates/forge-web/src/render/markdown.rs +++ b/crates/forge-web/src/render/markdown.rs @@ -1,4 +1,4 @@ -//! comrak + ammonia markdown rendering (see docs/m2-interfaces.md). +//! comrak + ammonia markdown rendering. //! //! Pipeline: parse with comrak (GFM extensions, raw HTML passed through), //! optionally rewrite link and image URLs in the AST, render to HTML, then diff --git a/crates/forge-web/src/self_update.rs b/crates/forge-web/src/self_update.rs new file mode 100644 index 0000000..f9f8966 --- /dev/null +++ b/crates/forge-web/src/self_update.rs @@ -0,0 +1,575 @@ +//! Self-update: a green CI run of the forge's own repo replaces the running binary and restarts. +//! +//! Event-driven. `maybe_deploy` runs from the runner finish path when a job finishes. Nothing +//! polls. After the swap the process exits with `RESTART_EXIT_CODE`, and the systemd unit +//! (`Restart=on-failure`) starts the new binary. +//! +//! Runners update the same way. The claim route advertises the running binary's sha256 to a runner +//! of the same target, and `GET /api/v1/ci/runners/binary` serves the bytes. + +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use forge_core::ci::{CiRun, RunState}; +use forge_core::config::SelfUpdateConfig; +use futures_util::StreamExt; +use futures_util::stream::BoxStream; +use http::header::{CONTENT_LENGTH, CONTENT_TYPE, HeaderValue}; +use http_body_util::StreamBody; +use sha2::{Digest, Sha256}; +use tokio::io::AsyncWriteExt; +use tokio_util::io::ReaderStream; +use topcoat::router::{Body, HeaderMap, StatusCode, response::Response}; + +use crate::state::AppState; + +/// Exit code after a swap. systemd `Restart=on-failure` restarts the unit on any non-zero exit. +pub const RESTART_EXIT_CODE: u8 = 75; +/// Response header carrying the sha256 of the running binary, lowercase hex. +pub const SHA_HEADER: &str = "Forge-Binary-Sha256"; +/// Request header a runner sends with its `-` target. +pub const TARGET_HEADER: &str = "Forge-Runner-Target"; +/// How long the staged binary may take to answer `--version`. +const SANITY_TIMEOUT: Duration = Duration::from_secs(10); + +/// Serialises deploys. A deploy that finds another one running is skipped. +static DEPLOY_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); +/// Wakes the server so it stops after a swap. +static RESTART: tokio::sync::Notify = tokio::sync::Notify::const_new(); +static RESTART_REQUESTED: AtomicBool = AtomicBool::new(false); + +/// The running binary, hashed once at startup. +pub struct Running { + /// The executable path, used to place the sibling `.prev`, `.bad` and staging files. + pub path: PathBuf, + pub sha256: String, +} + +static RUNNING: OnceLock> = OnceLock::new(); + +/// The running binary, hashed on first use. `None` if it cannot be read, which disables +/// advertising and serving, and deploys. +pub fn running() -> Option<&'static Running> { + RUNNING + .get_or_init(|| match load_running() { + Ok(running) => { + tracing::info!(sha256 = %running.sha256, "self-update: running binary hashed"); + Some(running) + } + Err(e) => { + tracing::error!(error = %e, "self-update: cannot hash the running binary"); + None + } + }) + .as_ref() +} + +fn load_running() -> std::io::Result { + let path = std::env::current_exe()?; + let sha256 = sha256_reader(std::fs::File::open(image_path())?)?; + Ok(Running { path, sha256 }) +} + +/// The file that holds the running image. On Linux that is `/proc/self/exe`, which still names the +/// old inode after a rename over the executable. Elsewhere it is the executable path. +fn image_path() -> PathBuf { + let proc_exe = PathBuf::from("/proc/self/exe"); + if proc_exe.exists() { + proc_exe + } else { + std::env::current_exe().unwrap_or(proc_exe) + } +} + +/// Resolves once a swap has asked the server to stop. +pub async fn restart_requested() { + RESTART.notified().await; +} + +/// Whether a swap asked the process to exit with `RESTART_EXIT_CODE`. +pub fn restart_pending() -> bool { + RESTART_REQUESTED.load(Ordering::SeqCst) +} + +/// `-` for this build, as a runner reports it in `Forge-Runner-Target`. +pub fn target() -> String { + format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS) +} + +/// Whether a runner's requested target is this build's target. +fn target_matches(requested: Option<&str>) -> bool { + requested == Some(target().as_str()) +} + +/// Whether a finished run should deploy. Pure, so the rules can be tested. A run deploys only when +/// it is a successful push to the configured branch of the configured repo, and it is still the +/// newest run on that branch. Pull request runs (including fork runs) never deploy. +pub fn should_deploy( + cfg: &SelfUpdateConfig, + repo_full_name: &str, + run: &CiRun, + newest_on_ref: Option<&str>, +) -> bool { + cfg.enabled + && matches!(run.state, RunState::Success) + && run.trigger == "push" + && run.pull_number.is_none() + && repo_full_name.eq_ignore_ascii_case(&cfg.repo) + && run.git_ref == format!("refs/heads/{}", cfg.branch) + && newest_on_ref == Some(run.id.as_str()) +} + +/// Why a candidate binary must not be installed, or `None` to install it. `bad_list` is the text +/// of `.bad`: one hex sha256 per line, `#` starts a comment. +pub fn skip_reason(candidate_sha: &str, running_sha: &str, bad_list: &str) -> Option<&'static str> { + if candidate_sha.eq_ignore_ascii_case(running_sha) { + return Some("same as the running binary"); + } + let listed = bad_list + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .any(|line| line.eq_ignore_ascii_case(candidate_sha)); + listed.then_some("listed in the bad list") +} + +/// `.` next to `exe`, for example `forge.prev`. +fn sibling(exe: &Path, suffix: &str) -> PathBuf { + let name = exe + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + exe.with_file_name(format!("{name}.{suffix}")) +} + +/// Called when a job finishes. Starts a deploy in the background when the run qualifies. +pub async fn maybe_deploy(state: &AppState, run: &CiRun) { + let cfg = &state.config.self_update; + if !cfg.enabled || !matches!(run.state, RunState::Success) { + return; + } + let repo = match state.store.repo_by_id(&run.repo_id).await { + Ok(Some(repo)) => repo, + Ok(None) => return, + Err(e) => { + tracing::error!(error = %e, "self-update: loading the repo failed"); + return; + } + }; + let full_name = format!("{}/{}", repo.owner_name, repo.name); + let newest = match state + .store + .latest_run_on_ref(&run.repo_id, &run.git_ref) + .await + { + Ok(newest) => newest, + Err(e) => { + tracing::error!(error = %e, "self-update: loading the newest run failed"); + return; + } + }; + if !should_deploy(cfg, &full_name, run, newest.as_ref().map(|r| r.id.as_str())) { + return; + } + tracing::info!(run_id = %run.id, "self-update: green push run on the deploy branch"); + let state = state.clone(); + let run = run.clone(); + tokio::spawn(async move { deploy(state, run).await }); +} + +/// Installs the run's artifact over the running binary and asks the server to restart. Logs and +/// returns on any failure, leaving the running binary in place. +pub async fn deploy(state: AppState, run: CiRun) { + let Ok(_guard) = DEPLOY_LOCK.try_lock() else { + tracing::info!(run_id = %run.id, "self-update: a deploy is already running, skipping"); + return; + }; + if let Err(e) = deploy_inner(&state, &run).await { + tracing::error!(run_id = %run.id, error = %e, "self-update: deploy failed"); + } +} + +async fn deploy_inner(state: &AppState, run: &CiRun) -> Result<(), String> { + let cfg = &state.config.self_update; + let running = running().ok_or("the running binary was not hashed at startup")?; + + let jobs = state + .store + .jobs_for_run(&run.id) + .await + .map_err(|e| e.to_string())?; + let Some(job) = jobs.iter().find(|job| job.name == cfg.job) else { + tracing::info!(run_id = %run.id, job = %cfg.job, "self-update: no such job in the run, skipping"); + return Ok(()); + }; + let artifact = state + .store + .artifact(&job.id, &cfg.artifact) + .await + .map_err(|e| e.to_string())?; + let Some(artifact) = artifact else { + tracing::info!(run_id = %run.id, artifact = %cfg.artifact, "self-update: no such artifact, skipping"); + return Ok(()); + }; + let read = state + .blobs + .read(&crate::ci::artifact_key(&artifact.id)) + .await + .map_err(|e| e.to_string())? + .ok_or("the artifact bytes are missing")?; + + // Stage next to the executable, so the final rename stays on one filesystem. + let staged = sibling(&running.path, "new"); + let sha = match write_staged(read.stream, &staged).await { + Ok(sha) => sha, + Err(e) => { + let _ = std::fs::remove_file(&staged); + return Err(e); + } + }; + if !sha.eq_ignore_ascii_case(&artifact.sha256) { + let _ = std::fs::remove_file(&staged); + return Err(format!( + "artifact sha256 {sha} does not match the recorded {}", + artifact.sha256 + )); + } + let bad = std::fs::read_to_string(sibling(&running.path, "bad")).unwrap_or_default(); + if let Some(reason) = skip_reason(&sha, &running.sha256, &bad) { + let _ = std::fs::remove_file(&staged); + tracing::info!(sha256 = %sha, reason, "self-update: skipped"); + return Ok(()); + } + if let Err(e) = sanity_check(&staged).await { + let _ = std::fs::remove_file(&staged); + return Err(e); + } + if let Err(e) = swap(&running.path, &staged) { + let _ = std::fs::remove_file(&staged); + return Err(e); + } + tracing::info!( + old_sha256 = %running.sha256, + new_sha256 = %sha, + exe = %running.path.display(), + "self-update: binary replaced, restarting" + ); + RESTART_REQUESTED.store(true, Ordering::SeqCst); + RESTART.notify_one(); + Ok(()) +} + +/// Streams the artifact to `path`, hashing as it goes. The file is executable and synced before +/// this returns. Returns the sha256 in lowercase hex. +async fn write_staged( + mut stream: BoxStream<'static, std::io::Result>, + path: &Path, +) -> Result { + use std::os::unix::fs::PermissionsExt; + + let mut file = tokio::fs::File::create(path) + .await + .map_err(|e| format!("cannot create {}: {e}", path.display()))?; + let mut hasher = Sha256::new(); + while let Some(chunk) = stream.next().await { + let chunk = chunk.map_err(|e| e.to_string())?; + hasher.update(&chunk); + file.write_all(&chunk).await.map_err(|e| e.to_string())?; + } + file.flush().await.map_err(|e| e.to_string())?; + file.sync_all().await.map_err(|e| e.to_string())?; + drop(file); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)) + .map_err(|e| e.to_string())?; + Ok(hex::encode(hasher.finalize())) +} + +/// Runs ` --version` with a timeout. Only exit 0 passes. +async fn sanity_check(path: &Path) -> Result<(), String> { + use std::process::Stdio; + + let mut child = tokio::process::Command::new(path) + .arg("--version") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .map_err(|e| format!("the new binary does not run: {e}"))?; + match tokio::time::timeout(SANITY_TIMEOUT, child.wait()).await { + Ok(Ok(status)) if status.success() => Ok(()), + Ok(Ok(status)) => Err(format!("the new binary exited with {status} for --version")), + Ok(Err(e)) => Err(format!("waiting for the new binary failed: {e}")), + Err(_) => Err("the new binary did not answer --version within 10 seconds".into()), + } +} + +/// Keeps the current binary as `.prev` (a hard link when possible), then renames `staged` +/// over `exe`. +fn swap(exe: &Path, staged: &Path) -> Result<(), String> { + let prev = sibling(exe, "prev"); + if prev.exists() { + std::fs::remove_file(&prev).map_err(|e| format!("cannot remove the old prev: {e}"))?; + } + if std::fs::hard_link(exe, &prev).is_err() { + std::fs::copy(exe, &prev).map_err(|e| format!("cannot keep the previous binary: {e}"))?; + } + std::fs::rename(staged, exe).map_err(|e| format!("cannot replace the binary: {e}")) +} + +/// Whether a claim response should advertise the binary: self-update is on and the runner asked +/// for this target. Adds `Forge-Binary-Sha256` to a 200 or 204 response. +pub fn advertise(state: &AppState, request: &HeaderMap, res: &mut Response) { + if !state.config.self_update.enabled { + return; + } + if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) { + return; + } + let requested = request.get(TARGET_HEADER).and_then(|v| v.to_str().ok()); + if !target_matches(requested) { + return; + } + let Some(running) = running() else { + return; + }; + if let Ok(value) = HeaderValue::from_str(&running.sha256) { + res.headers_mut().insert(SHA_HEADER, value); + } +} + +/// The running binary as a streamed response, with its sha256. The caller checks auth and that +/// self-update is enabled. `Err` when the binary cannot be read. +pub async fn binary_response() -> Result { + let running = running().ok_or("the running binary was not hashed at startup")?; + let file = tokio::fs::File::open(image_path()) + .await + .map_err(|e| e.to_string())?; + let len = file.metadata().await.map_err(|e| e.to_string())?.len(); + let frames = ReaderStream::new(file).map(|chunk| chunk.map(http_body::Frame::data)); + let mut res = Response::new(Body::new(StreamBody::new(frames))); + let headers = res.headers_mut(); + headers.insert( + CONTENT_TYPE, + HeaderValue::from_static("application/octet-stream"), + ); + headers.insert(CONTENT_LENGTH, HeaderValue::from(len)); + if let Ok(value) = HeaderValue::from_str(&running.sha256) { + headers.insert(SHA_HEADER, value); + } + Ok(res) +} + +fn sha256_reader(mut reader: impl std::io::Read) -> std::io::Result { + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 64 * 1024]; + loop { + let n = reader.read(&mut buf)?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + } + Ok(hex::encode(hasher.finalize())) +} + +#[cfg(test)] +mod tests { + use super::*; + use forge_core::ci::CiRun; + + fn cfg() -> SelfUpdateConfig { + SelfUpdateConfig { + enabled: true, + repo: "Tahinli/forge".into(), + branch: "main".into(), + job: "build".into(), + artifact: "dist_forge".into(), + } + } + + fn run(trigger: &str, git_ref: &str, state: RunState, pull_number: Option) -> CiRun { + CiRun { + id: "run-7".into(), + repo_id: "repo-1".into(), + number: 7, + trigger: trigger.into(), + git_ref: git_ref.into(), + commit_oid: "a".repeat(40), + pull_number, + actor_id: "user-1".into(), + state, + config_error: None, + created_at: "now".into(), + finished_at: None, + } + } + + /// A push run of the deploy branch that is still the newest run. + fn good() -> CiRun { + run("push", "refs/heads/main", RunState::Success, None) + } + + #[test] + fn push_run_on_the_branch_of_the_repo_deploys() { + assert!(should_deploy( + &cfg(), + "Tahinli/forge", + &good(), + Some("run-7") + )); + } + + #[test] + fn pull_request_runs_never_deploy() { + // A PR run carries a pull number and a refs/pull ref, and its trigger is not "push". + let pr = run( + "pull_request", + "refs/pull/3/head", + RunState::Success, + Some(3), + ); + assert!(!should_deploy(&cfg(), "Tahinli/forge", &pr, Some("run-7"))); + // Even if a PR run were stored on the branch ref, the trigger and pull number exclude it. + let pr_on_branch = run( + "pull_request", + "refs/heads/main", + RunState::Success, + Some(3), + ); + assert!(!should_deploy( + &cfg(), + "Tahinli/forge", + &pr_on_branch, + Some("run-7") + )); + let push_with_pull = run("push", "refs/heads/main", RunState::Success, Some(3)); + assert!(!should_deploy( + &cfg(), + "Tahinli/forge", + &push_with_pull, + Some("run-7") + )); + } + + #[test] + fn other_branch_tag_and_manual_runs_do_not_deploy() { + let feature = run("push", "refs/heads/feature", RunState::Success, None); + assert!(!should_deploy( + &cfg(), + "Tahinli/forge", + &feature, + Some("run-7") + )); + let tag = run("tag", "refs/tags/v1", RunState::Success, None); + assert!(!should_deploy(&cfg(), "Tahinli/forge", &tag, Some("run-7"))); + let manual = run("manual", "refs/heads/main", RunState::Success, None); + assert!(!should_deploy( + &cfg(), + "Tahinli/forge", + &manual, + Some("run-7") + )); + } + + #[test] + fn other_repo_does_not_deploy() { + assert!(!should_deploy( + &cfg(), + "Tahinli/other", + &good(), + Some("run-7") + )); + // Case differences in the owner or name still match the configured repo. + assert!(should_deploy( + &cfg(), + "tahinli/FORGE", + &good(), + Some("run-7") + )); + } + + #[test] + fn only_a_successful_run_deploys() { + for state in [ + RunState::Failure, + RunState::Cancelled, + RunState::Error, + RunState::Running, + ] { + let r = run("push", "refs/heads/main", state, None); + assert!(!should_deploy(&cfg(), "Tahinli/forge", &r, Some("run-7"))); + } + } + + #[test] + fn an_older_run_on_the_branch_does_not_deploy() { + assert!(!should_deploy( + &cfg(), + "Tahinli/forge", + &good(), + Some("run-9") + )); + assert!(!should_deploy(&cfg(), "Tahinli/forge", &good(), None)); + } + + #[test] + fn disabled_config_never_deploys() { + let mut off = cfg(); + off.enabled = false; + assert!(!should_deploy( + &off, + "Tahinli/forge", + &good(), + Some("run-7") + )); + } + + #[test] + fn same_sha_as_running_is_skipped() { + let sha = "ab12"; + assert_eq!( + skip_reason(sha, sha, ""), + Some("same as the running binary") + ); + assert_eq!( + skip_reason("AB12", sha, ""), + Some("same as the running binary") + ); + assert_eq!(skip_reason("cd34", sha, ""), None); + } + + #[test] + fn bad_list_entries_are_skipped() { + let bad = "# rolled back 2026-10-01\n1111\n 2222 \n\n"; + assert_eq!( + skip_reason("2222", "ffff", bad), + Some("listed in the bad list") + ); + assert_eq!( + skip_reason("1111", "ffff", bad), + Some("listed in the bad list") + ); + // A comment line is not a sha. + assert_eq!(skip_reason("rolled", "ffff", bad), None); + assert_eq!(skip_reason("3333", "ffff", bad), None); + } + + #[test] + fn target_must_match_this_build() { + assert!(target_matches(Some(&target()))); + assert!(!target_matches(None)); + assert!(!target_matches(Some("riscv64-plan9"))); + } + + #[test] + fn sha256_of_known_bytes() { + let digest = sha256_reader(&b"abc"[..]).unwrap(); + assert_eq!( + digest, + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + } +} diff --git a/crates/forge-web/src/state.rs b/crates/forge-web/src/state.rs index 7d69f9d..1cfcda3 100644 --- a/crates/forge-web/src/state.rs +++ b/crates/forge-web/src/state.rs @@ -41,4 +41,8 @@ pub struct AppState { pub mailer: Arc, /// Wakes the mail worker when a message is queued or the mail settings change. pub mail_waker: Arc, + /// Open notification streams per user. A change to an inbox publishes the new unread count. + pub notify_hub: Arc, + /// Change counters of CI jobs and runs. Log followers and run pages wait on them. + pub ci_live: Arc, } diff --git a/crates/forge-web/src/test_support.rs b/crates/forge-web/src/test_support.rs index d8cffff..355419e 100644 --- a/crates/forge-web/src/test_support.rs +++ b/crates/forge-web/src/test_support.rs @@ -51,6 +51,7 @@ pub fn test_config(dir: &Path) -> Config { advisories: Default::default(), mail: Default::default(), orgs: Default::default(), + self_update: Default::default(), } } @@ -78,6 +79,8 @@ pub async fn test_state(dir: &Path) -> AppState { ci_waker: Arc::new(Notify::new()), mailer: Arc::new(crate::mail::FakeMailer::default()), mail_waker: Arc::new(Notify::new()), + notify_hub: Arc::new(crate::notify_hub::NotifyHub::new()), + ci_live: Arc::new(crate::ci::CiLive::default()), } } diff --git a/crates/forge-web/src/webhooks/payload.rs b/crates/forge-web/src/webhooks/payload.rs index 0086612..72bda37 100644 --- a/crates/forge-web/src/webhooks/payload.rs +++ b/crates/forge-web/src/webhooks/payload.rs @@ -1,7 +1,7 @@ //! JSON payload builders for webhook deliveries. Each builder returns the event-specific fields. //! `emit` adds `action` (when the event has one), `repository` and `sender`. //! -//! The shapes follow docs/webhooks-interfaces.md. Links are built from `base_url` (the configured +//! Links are built from `base_url` (the configured //! public URL), so they point at the instance a receiver can reach. use forge_core::{Comment, Issue, PullRequest, Repo, Review, Visibility}; diff --git a/crates/forge-web/tests/ci_e2e.rs b/crates/forge-web/tests/ci_e2e.rs index 2e6daed..b80d9b7 100644 --- a/crates/forge-web/tests/ci_e2e.rs +++ b/crates/forge-web/tests/ci_e2e.rs @@ -420,6 +420,7 @@ impl Worker { .claim(&self.secret, &self.labels) .await .expect("claim") + .job } /// Claims and runs jobs until the forge has nothing left. Returns how many ran. @@ -471,6 +472,8 @@ async fn register_runner(b: &Booted, admin_session: &str, name: &str) -> Worker images: forge_runner::config::ImagesConfig::default(), sandbox: forge_runner::config::SandboxConfig::default(), registries: Vec::new(), + // The e2e runner must not replace the test binary under itself. + auto_update: false, }; let runner = Runner::new(config, Arc::new(HostExecutor), RunOptions::default()).expect("runner"); diff --git a/deploy/user/forge-rollback b/deploy/user/forge-rollback new file mode 100755 index 0000000..feb5895 --- /dev/null +++ b/deploy/user/forge-rollback @@ -0,0 +1,27 @@ +#!/bin/sh +# Roll back ~/bin/forge to ~/bin/forge.prev after a unit failed. +# Usage: forge-rollback . Output goes to the journal. +set -eu + +unit="${1:?usage: forge-rollback }" +bin="$HOME/bin/forge" +prev="$bin.prev" +bad="$bin.bad" + +if [ ! -e "$prev" ]; then + echo "forge-rollback: $unit failed and $prev does not exist, nothing to roll back" + exit 0 +fi + +sha=$(sha256sum "$bin" | cut -d' ' -f1) +# Keep one hash per line, even if the file was edited by hand without a final newline. +if [ -s "$bad" ] && [ -n "$(tail -c 1 "$bad")" ]; then + echo >> "$bad" +fi +echo "$sha" >> "$bad" +mv -f "$prev" "$bin" +echo "forge-rollback: $unit failed, marked $sha bad, restored $prev" + +systemctl --user reset-failed "$unit" +systemctl --user start "$unit" +echo "forge-rollback: started $unit on the previous binary" diff --git a/deploy/user/forge-rollback.service b/deploy/user/forge-rollback.service new file mode 100644 index 0000000..e2e9159 --- /dev/null +++ b/deploy/user/forge-rollback.service @@ -0,0 +1,6 @@ +[Unit] +Description=roll back forge after forge.service failed + +[Service] +Type=oneshot +ExecStart=%h/bin/forge-rollback forge.service diff --git a/deploy/user/forge-runner-rollback.service b/deploy/user/forge-runner-rollback.service new file mode 100644 index 0000000..fee0a6c --- /dev/null +++ b/deploy/user/forge-runner-rollback.service @@ -0,0 +1,6 @@ +[Unit] +Description=roll back forge runner after forge-runner.service failed + +[Service] +Type=oneshot +ExecStart=%h/bin/forge-rollback forge-runner.service diff --git a/deploy/user/forge-runner.service b/deploy/user/forge-runner.service new file mode 100644 index 0000000..8f3de8b --- /dev/null +++ b/deploy/user/forge-runner.service @@ -0,0 +1,18 @@ +[Unit] +Description=forge CI runner +After=network-online.target +Wants=network-online.target +# Crash loops stop the unit: 3 starts within 60s, then it enters failed and OnFailure runs the rollback. +StartLimitIntervalSec=60 +StartLimitBurst=3 +OnFailure=forge-runner-rollback.service + +[Service] +ExecStart=%h/bin/forge runner run --config %h/.config/forge-runner/runner.toml +# A self-update exits with code 75, which is non-zero, so Restart=on-failure restarts it into the new binary. +Restart=on-failure +RestartSec=10 +TimeoutStopSec=120 + +[Install] +WantedBy=default.target diff --git a/deploy/user/forge.service b/deploy/user/forge.service new file mode 100644 index 0000000..0758818 --- /dev/null +++ b/deploy/user/forge.service @@ -0,0 +1,20 @@ +[Unit] +Description=forge +After=network-online.target +# Crash loops stop the unit: 3 starts within 60s, then it enters failed and OnFailure runs the rollback. +StartLimitIntervalSec=60 +StartLimitBurst=3 +OnFailure=forge-rollback.service + +[Service] +WorkingDirectory=%h +Environment=FORGE_CONFIG=%h/config/forge.toml +ExecStart=%h/bin/forge serve +# A self-update exits with code 75, which is non-zero, so Restart=on-failure restarts it into the new binary. +Restart=on-failure +RestartSec=2 +NoNewPrivileges=yes +LimitNOFILE=65536 + +[Install] +WantedBy=default.target