forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·9.7 MiB·37e985d·Tahinli·2 hours ago·363 commits
| 1 | use std::io::Read; |
| 2 | use std::os::unix::fs::PermissionsExt; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | use std::process::Stdio; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | use sha2::{Digest, Sha256}; |
| 8 | |
| 9 | use crate::client::{ClientError, ForgeClient}; |
| 10 | |
| 11 | pub use forge_ci::proto::RESTART_EXIT_CODE; |
| 12 | |
| 13 | const SMOKE_TIMEOUT: Duration = Duration::from_secs(10); |
| 14 | const NEW_NAME: &str = ".forge-runner.new"; |
| 15 | const PREV_SUFFIX: &str = ".prev"; |
| 16 | const BAD_SUFFIX: &str = ".bad"; |
| 17 | |
| 18 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 19 | pub struct UpdateState { |
| 20 | enabled: bool, |
| 21 | current: Option<String>, |
| 22 | pending: Option<String>, |
| 23 | given_up: Option<String>, |
| 24 | } |
| 25 | |
| 26 | impl UpdateState { |
| 27 | pub fn new(auto_update: bool, current: Option<String>) -> Self { |
| 28 | Self { |
| 29 | enabled: auto_update && current.is_some(), |
| 30 | current, |
| 31 | pending: None, |
| 32 | given_up: None, |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | pub fn observe(&mut self, advertised: Option<&str>) -> bool { |
| 37 | if !self.enabled { |
| 38 | return false; |
| 39 | } |
| 40 | let Some(advertised) = advertised else { |
| 41 | return false; |
| 42 | }; |
| 43 | if Some(advertised) == self.current.as_deref() |
| 44 | || Some(advertised) == self.given_up.as_deref() |
| 45 | { |
| 46 | self.pending = None; |
| 47 | return false; |
| 48 | } |
| 49 | if self.pending.as_deref() == Some(advertised) { |
| 50 | return false; |
| 51 | } |
| 52 | self.pending = Some(advertised.to_owned()); |
| 53 | true |
| 54 | } |
| 55 | |
| 56 | pub fn enabled(&self) -> bool { |
| 57 | self.enabled |
| 58 | } |
| 59 | |
| 60 | pub fn pending(&self) -> Option<&str> { |
| 61 | self.pending.as_deref() |
| 62 | } |
| 63 | |
| 64 | pub fn give_up(&mut self, sha: &str) { |
| 65 | self.given_up = Some(sha.to_owned()); |
| 66 | self.pending = None; |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | pub fn is_listed_bad(list: &str, sha: &str) -> bool { |
| 71 | list.lines() |
| 72 | .any(|line| line.trim().eq_ignore_ascii_case(sha)) |
| 73 | } |
| 74 | |
| 75 | pub fn file_sha256(path: &Path) -> std::io::Result<String> { |
| 76 | let mut file = std::fs::File::open(path)?; |
| 77 | let mut hasher = Sha256::new(); |
| 78 | let mut buf = vec![0u8; 64 * 1024]; |
| 79 | loop { |
| 80 | let n = file.read(&mut buf)?; |
| 81 | if n == 0 { |
| 82 | break; |
| 83 | } |
| 84 | hasher.update(&buf[..n]); |
| 85 | } |
| 86 | Ok(hex::encode(hasher.finalize())) |
| 87 | } |
| 88 | |
| 89 | pub fn locate_self() -> std::io::Result<(PathBuf, String)> { |
| 90 | let exe = std::env::current_exe()?; |
| 91 | let sha = file_sha256(&exe)?; |
| 92 | Ok((exe, sha)) |
| 93 | } |
| 94 | |
| 95 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 96 | pub enum Installed { |
| 97 | Replaced, |
| 98 | Listed, |
| 99 | } |
| 100 | |
| 101 | #[derive(Debug, thiserror::Error)] |
| 102 | pub enum UpdateError { |
| 103 | #[error("local io: {0}")] |
| 104 | Io(#[from] std::io::Error), |
| 105 | #[error("download: {0}")] |
| 106 | Download(#[from] ClientError), |
| 107 | #[error("sha256 mismatch: forge advertised {expected}, downloaded {actual}")] |
| 108 | Mismatch { expected: String, actual: String }, |
| 109 | #[error("new binary failed its check: {0}")] |
| 110 | Smoke(String), |
| 111 | } |
| 112 | |
| 113 | pub async fn install( |
| 114 | client: &ForgeClient, |
| 115 | runner_secret: &str, |
| 116 | exe: &Path, |
| 117 | expected: &str, |
| 118 | ) -> Result<Installed, UpdateError> { |
| 119 | let new = exe.with_file_name(NEW_NAME); |
| 120 | let _ = std::fs::remove_file(&new); |
| 121 | let result = stage_and_swap(client, runner_secret, exe, &new, expected).await; |
| 122 | if !matches!(result, Ok(Installed::Replaced)) { |
| 123 | let _ = std::fs::remove_file(&new); |
| 124 | } |
| 125 | result |
| 126 | } |
| 127 | |
| 128 | async fn stage_and_swap( |
| 129 | client: &ForgeClient, |
| 130 | runner_secret: &str, |
| 131 | exe: &Path, |
| 132 | new: &Path, |
| 133 | expected: &str, |
| 134 | ) -> Result<Installed, UpdateError> { |
| 135 | let actual = client.download_binary(runner_secret, new).await?; |
| 136 | if actual != expected { |
| 137 | return Err(UpdateError::Mismatch { |
| 138 | expected: expected.to_owned(), |
| 139 | actual, |
| 140 | }); |
| 141 | } |
| 142 | std::fs::set_permissions(new, std::fs::Permissions::from_mode(0o755))?; |
| 143 | std::fs::File::open(new)?.sync_all()?; |
| 144 | smoke_test(new).await?; |
| 145 | |
| 146 | let bad = match std::fs::read_to_string(sibling(exe, BAD_SUFFIX)) { |
| 147 | Ok(list) => list, |
| 148 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(), |
| 149 | Err(e) => return Err(e.into()), |
| 150 | }; |
| 151 | if is_listed_bad(&bad, expected) { |
| 152 | return Ok(Installed::Listed); |
| 153 | } |
| 154 | |
| 155 | let prev = sibling(exe, PREV_SUFFIX); |
| 156 | match std::fs::remove_file(&prev) { |
| 157 | Ok(()) => {} |
| 158 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} |
| 159 | Err(e) => return Err(e.into()), |
| 160 | } |
| 161 | if std::fs::hard_link(exe, &prev).is_err() { |
| 162 | std::fs::copy(exe, &prev)?; |
| 163 | } |
| 164 | std::fs::rename(new, exe)?; |
| 165 | Ok(Installed::Replaced) |
| 166 | } |
| 167 | |
| 168 | async fn smoke_test(bin: &Path) -> Result<(), UpdateError> { |
| 169 | let output = tokio::time::timeout( |
| 170 | SMOKE_TIMEOUT, |
| 171 | tokio::process::Command::new(bin) |
| 172 | .arg("--version") |
| 173 | .stdin(Stdio::null()) |
| 174 | .kill_on_drop(true) |
| 175 | .output(), |
| 176 | ) |
| 177 | .await |
| 178 | .map_err(|_| UpdateError::Smoke("--version did not finish in time".into()))??; |
| 179 | if !output.status.success() { |
| 180 | return Err(UpdateError::Smoke(format!( |
| 181 | "--version exited with {}", |
| 182 | output.status |
| 183 | ))); |
| 184 | } |
| 185 | Ok(()) |
| 186 | } |
| 187 | |
| 188 | fn sibling(exe: &Path, suffix: &str) -> PathBuf { |
| 189 | let mut name = exe.as_os_str().to_owned(); |
| 190 | name.push(suffix); |
| 191 | PathBuf::from(name) |
| 192 | } |
| 193 | |
| 194 | #[cfg(test)] |
| 195 | mod tests { |
| 196 | use super::*; |
| 197 | |
| 198 | const OURS: &str = "aaaa"; |
| 199 | const THEIRS: &str = "bbbb"; |
| 200 | |
| 201 | fn state(auto_update: bool) -> UpdateState { |
| 202 | UpdateState::new(auto_update, Some(OURS.to_owned())) |
| 203 | } |
| 204 | |
| 205 | #[test] |
| 206 | fn a_different_sha_becomes_pending_once() { |
| 207 | let mut s = state(true); |
| 208 | assert!(s.observe(Some(THEIRS))); |
| 209 | assert_eq!(s.pending(), Some(THEIRS)); |
| 210 | assert!(!s.observe(Some(THEIRS))); |
| 211 | assert_eq!(s.pending(), Some(THEIRS)); |
| 212 | } |
| 213 | |
| 214 | #[test] |
| 215 | fn matching_sha_or_no_header_leaves_nothing_pending() { |
| 216 | let mut s = state(true); |
| 217 | assert!(!s.observe(Some(OURS))); |
| 218 | assert_eq!(s.pending(), None); |
| 219 | assert!(!s.observe(None)); |
| 220 | assert_eq!(s.pending(), None); |
| 221 | } |
| 222 | |
| 223 | #[test] |
| 224 | fn absent_header_keeps_a_pending_update() { |
| 225 | let mut s = state(true); |
| 226 | s.observe(Some(THEIRS)); |
| 227 | s.observe(None); |
| 228 | assert_eq!(s.pending(), Some(THEIRS)); |
| 229 | } |
| 230 | |
| 231 | #[test] |
| 232 | fn disabled_or_unknown_current_never_pends() { |
| 233 | let mut off = state(false); |
| 234 | assert!(!off.observe(Some(THEIRS))); |
| 235 | assert_eq!(off.pending(), None); |
| 236 | |
| 237 | let mut unknown = UpdateState::new(true, None); |
| 238 | assert!(!unknown.observe(Some(THEIRS))); |
| 239 | assert_eq!(unknown.pending(), None); |
| 240 | } |
| 241 | |
| 242 | #[test] |
| 243 | fn a_failed_sha_is_not_retried_until_the_forge_moves_on() { |
| 244 | let mut s = state(true); |
| 245 | s.observe(Some(THEIRS)); |
| 246 | s.give_up(THEIRS); |
| 247 | assert_eq!(s.pending(), None); |
| 248 | |
| 249 | assert!(!s.observe(Some(THEIRS))); |
| 250 | assert_eq!(s.pending(), None); |
| 251 | |
| 252 | assert!(s.observe(Some("cccc"))); |
| 253 | assert_eq!(s.pending(), Some("cccc")); |
| 254 | } |
| 255 | |
| 256 | #[test] |
| 257 | fn going_back_to_the_failed_sha_cancels_a_pending_update() { |
| 258 | let mut s = state(true); |
| 259 | s.observe(Some(THEIRS)); |
| 260 | s.give_up(THEIRS); |
| 261 | s.observe(Some("cccc")); |
| 262 | s.observe(Some(THEIRS)); |
| 263 | assert_eq!(s.pending(), None); |
| 264 | } |
| 265 | |
| 266 | #[test] |
| 267 | fn bad_list_matches_whole_lines_case_insensitively() { |
| 268 | let list = "# comment is not a sha\nBBBB\n cccc \n"; |
| 269 | assert!(is_listed_bad(list, THEIRS)); |
| 270 | assert!(is_listed_bad(list, "cccc")); |
| 271 | assert!(!is_listed_bad(list, "bbb")); |
| 272 | assert!(!is_listed_bad("", THEIRS)); |
| 273 | } |
| 274 | |
| 275 | #[test] |
| 276 | fn sibling_appends_the_suffix() { |
| 277 | assert_eq!( |
| 278 | sibling(Path::new("/home/t/.local/bin/forge"), PREV_SUFFIX), |
| 279 | PathBuf::from("/home/t/.local/bin/forge.prev") |
| 280 | ); |
| 281 | } |
| 282 | |
| 283 | #[test] |
| 284 | fn file_sha256_matches_a_known_digest() { |
| 285 | let dir = tempfile::tempdir().expect("tempdir"); |
| 286 | let path = dir.path().join("f"); |
| 287 | std::fs::write(&path, b"abc").expect("write"); |
| 288 | assert_eq!( |
| 289 | file_sha256(&path).expect("hash"), |
| 290 | "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" |
| 291 | ); |
| 292 | } |
| 293 | } |