| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | use std::path::Path; |
| 7 | use std::time::Duration; |
| 8 | |
| 9 | use forge_ci::proto::{ |
| 10 | BUILD_HEADER, CAP_REQUEUE, CAP_RESTART, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, |
| 11 | HeartbeatResponse, JobAssignment, MEMORY_BUDGET_HEADER, RESERVE_MEMORY_HEADER, RESTART_HEADER, |
| 12 | RegisterRequest, RegisterResponse, RequeueRequest, RestartMode, RunnerConfigOverrides, |
| 13 | RunnerConfigReport, |
| 14 | }; |
| 15 | use reqwest::StatusCode; |
| 16 | use reqwest::header::{CONTENT_LENGTH, HeaderMap}; |
| 17 | use serde::de::DeserializeOwned; |
| 18 | use sha2::{Digest, Sha256}; |
| 19 | use tokio::io::AsyncWriteExt; |
| 20 | |
| 21 | |
| 22 | pub const CLAIM_TIMEOUT: Duration = Duration::from_secs(35); |
| 23 | const REQUEST_TIMEOUT: Duration = Duration::from_secs(60); |
| 24 | const LOG_TIMEOUT: Duration = Duration::from_secs(60); |
| 25 | const ARTIFACT_TIMEOUT: Duration = Duration::from_secs(60 * 60); |
| 26 | const BINARY_TIMEOUT: Duration = Duration::from_secs(10 * 60); |
| 27 | const HEADER_LOG_OFFSET: &str = "X-Forge-Log-Offset"; |
| 28 | const HEADER_LOG_SIZE: &str = "X-Forge-Log-Size"; |
| 29 | |
| 30 | const HEADER_RUNNER_TARGET: &str = "Forge-Runner-Target"; |
| 31 | |
| 32 | const HEADER_BINARY_SHA256: &str = "Forge-Binary-Sha256"; |
| 33 | |
| 34 | const BINARY_PATH: &str = "/api/v1/ci/runners/binary"; |
| 35 | const CONFIG_PATH: &str = "/api/v1/ci/runners/config"; |
| 36 | |
| 37 | |
| 38 | #[derive(Debug, thiserror::Error)] |
| 39 | pub enum ClientError { |
| 40 | #[error("http: {0}")] |
| 41 | Http(#[from] reqwest::Error), |
| 42 | #[error("forge answered {status}: {body}")] |
| 43 | Status { status: StatusCode, body: String }, |
| 44 | #[error("local io: {0}")] |
| 45 | Io(#[from] std::io::Error), |
| 46 | #[error("protocol: {0}")] |
| 47 | Protocol(String), |
| 48 | } |
| 49 | |
| 50 | |
| 51 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 52 | pub enum LogAck { |
| 53 | |
| 54 | Accepted, |
| 55 | |
| 56 | Resync(u64), |
| 57 | } |
| 58 | |
| 59 | |
| 60 | #[derive(Clone, Debug)] |
| 61 | pub struct ClaimReply { |
| 62 | |
| 63 | pub job: Option<JobAssignment>, |
| 64 | |
| 65 | pub binary_sha256: Option<String>, |
| 66 | |
| 67 | pub concurrency: Option<u32>, |
| 68 | |
| 69 | pub restart: Option<RestartMode>, |
| 70 | |
| 71 | pub memory_budget: Option<String>, |
| 72 | |
| 73 | pub reserve_memory: Option<String>, |
| 74 | } |
| 75 | |
| 76 | |
| 77 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 78 | pub struct MemoryClaim { |
| 79 | |
| 80 | pub free: u64, |
| 81 | pub budget: u64, |
| 82 | |
| 83 | pub reserve: u64, |
| 84 | } |
| 85 | |
| 86 | |
| 87 | #[derive(Clone, Debug)] |
| 88 | pub struct ForgeClient { |
| 89 | http: reqwest::Client, |
| 90 | base: String, |
| 91 | } |
| 92 | |
| 93 | impl ForgeClient { |
| 94 | |
| 95 | pub fn new(base_url: &str) -> Result<Self, ClientError> { |
| 96 | let http = reqwest::Client::builder() |
| 97 | .user_agent(concat!("forge-runner/", env!("CARGO_PKG_VERSION"))) |
| 98 | .connect_timeout(Duration::from_secs(10)) |
| 99 | .build()?; |
| 100 | Ok(Self { |
| 101 | http, |
| 102 | base: base_url.trim_end_matches('/').to_owned(), |
| 103 | }) |
| 104 | } |
| 105 | |
| 106 | fn url(&self, path: &str) -> String { |
| 107 | format!("{}{}", self.base, path) |
| 108 | } |
| 109 | |
| 110 | |
| 111 | pub async fn register(&self, req: &RegisterRequest) -> Result<RegisterResponse, ClientError> { |
| 112 | let resp = self |
| 113 | .http |
| 114 | .post(self.url("/api/v1/ci/runners/register")) |
| 115 | .json(req) |
| 116 | .timeout(REQUEST_TIMEOUT) |
| 117 | .send() |
| 118 | .await?; |
| 119 | json_or_error(resp).await |
| 120 | } |
| 121 | |
| 122 | |
| 123 | pub async fn claim( |
| 124 | &self, |
| 125 | runner_secret: &str, |
| 126 | labels: &[String], |
| 127 | ) -> Result<ClaimReply, ClientError> { |
| 128 | self.claim_with(runner_secret, labels, None, None).await |
| 129 | } |
| 130 | |
| 131 | |
| 132 | |
| 133 | pub async fn claim_with( |
| 134 | &self, |
| 135 | runner_secret: &str, |
| 136 | labels: &[String], |
| 137 | concurrency: Option<usize>, |
| 138 | memory: Option<MemoryClaim>, |
| 139 | ) -> Result<ClaimReply, ClientError> { |
| 140 | let host = host_facts(); |
| 141 | let req = ClaimRequest { |
| 142 | labels: labels.to_vec(), |
| 143 | concurrency: concurrency.and_then(|n| u32::try_from(n).ok()), |
| 144 | version: Some(env!("CARGO_PKG_VERSION").to_owned()), |
| 145 | cpus: host.cpus, |
| 146 | memory_bytes: host.memory_bytes, |
| 147 | build: Some(forge_ci::build::display()), |
| 148 | boot_id: Some(crate::restart::boot_id().to_owned()), |
| 149 | capabilities: vec![CAP_RESTART.to_owned(), CAP_REQUEUE.to_owned()], |
| 150 | free_memory_bytes: memory.map(|m| m.free), |
| 151 | memory_budget_bytes: memory.map(|m| m.budget), |
| 152 | reserve_memory_bytes: memory.map(|m| m.reserve), |
| 153 | }; |
| 154 | let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS); |
| 155 | let resp = self |
| 156 | .http |
| 157 | .post(self.url("/api/v1/ci/runners/claim")) |
| 158 | .bearer_auth(runner_secret) |
| 159 | .header(HEADER_RUNNER_TARGET, target) |
| 160 | .json(&req) |
| 161 | .timeout(CLAIM_TIMEOUT) |
| 162 | .send() |
| 163 | .await?; |
| 164 | let binary_sha256 = advertised_sha256(resp.headers()); |
| 165 | let concurrency = advertised_concurrency(resp.headers()); |
| 166 | let restart = advertised_restart(resp.headers()); |
| 167 | let memory_budget = header_text(resp.headers(), MEMORY_BUDGET_HEADER); |
| 168 | let reserve_memory = header_text(resp.headers(), RESERVE_MEMORY_HEADER); |
| 169 | match resp.status() { |
| 170 | StatusCode::NO_CONTENT => Ok(ClaimReply { |
| 171 | job: None, |
| 172 | binary_sha256, |
| 173 | concurrency, |
| 174 | restart, |
| 175 | memory_budget, |
| 176 | reserve_memory, |
| 177 | }), |
| 178 | status if status.is_success() => Ok(ClaimReply { |
| 179 | job: Some(resp.json().await?), |
| 180 | binary_sha256, |
| 181 | concurrency, |
| 182 | restart, |
| 183 | memory_budget, |
| 184 | reserve_memory, |
| 185 | }), |
| 186 | _ => Err(status_error(resp).await), |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | |
| 191 | pub async fn get_config( |
| 192 | &self, |
| 193 | runner_secret: &str, |
| 194 | ) -> Result<RunnerConfigOverrides, ClientError> { |
| 195 | let resp = self |
| 196 | .http |
| 197 | .get(self.url(CONFIG_PATH)) |
| 198 | .bearer_auth(runner_secret) |
| 199 | .timeout(REQUEST_TIMEOUT) |
| 200 | .send() |
| 201 | .await?; |
| 202 | json_or_error(resp).await |
| 203 | } |
| 204 | |
| 205 | |
| 206 | pub async fn put_config( |
| 207 | &self, |
| 208 | runner_secret: &str, |
| 209 | report: &RunnerConfigReport, |
| 210 | ) -> Result<RunnerConfigOverrides, ClientError> { |
| 211 | let resp = self |
| 212 | .http |
| 213 | .put(self.url(CONFIG_PATH)) |
| 214 | .bearer_auth(runner_secret) |
| 215 | .json(report) |
| 216 | .timeout(REQUEST_TIMEOUT) |
| 217 | .send() |
| 218 | .await?; |
| 219 | json_or_error(resp).await |
| 220 | } |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | pub async fn download_binary( |
| 226 | &self, |
| 227 | runner_secret: &str, |
| 228 | dest: &Path, |
| 229 | ) -> Result<String, ClientError> { |
| 230 | let mut resp = self |
| 231 | .http |
| 232 | .get(self.url(BINARY_PATH)) |
| 233 | .bearer_auth(runner_secret) |
| 234 | .timeout(BINARY_TIMEOUT) |
| 235 | .send() |
| 236 | .await?; |
| 237 | if !resp.status().is_success() { |
| 238 | return Err(status_error(resp).await); |
| 239 | } |
| 240 | let mut file = tokio::fs::File::create(dest).await?; |
| 241 | let mut hasher = Sha256::new(); |
| 242 | while let Some(chunk) = resp.chunk().await? { |
| 243 | hasher.update(&chunk); |
| 244 | file.write_all(&chunk).await?; |
| 245 | } |
| 246 | file.flush().await?; |
| 247 | Ok(hex::encode(hasher.finalize())) |
| 248 | } |
| 249 | |
| 250 | |
| 251 | pub async fn post_logs( |
| 252 | &self, |
| 253 | job_id: &str, |
| 254 | job_token: &str, |
| 255 | offset: u64, |
| 256 | body: Vec<u8>, |
| 257 | ) -> Result<LogAck, ClientError> { |
| 258 | let resp = self |
| 259 | .http |
| 260 | .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/logs"))) |
| 261 | .bearer_auth(job_token) |
| 262 | .header(HEADER_LOG_OFFSET, offset.to_string()) |
| 263 | .header(reqwest::header::CONTENT_TYPE, "text/plain; charset=utf-8") |
| 264 | .body(body) |
| 265 | .timeout(LOG_TIMEOUT) |
| 266 | .send() |
| 267 | .await?; |
| 268 | match resp.status() { |
| 269 | StatusCode::CONFLICT => { |
| 270 | let size = resp |
| 271 | .headers() |
| 272 | .get(HEADER_LOG_SIZE) |
| 273 | .and_then(|v| v.to_str().ok()) |
| 274 | .and_then(|v| v.parse::<u64>().ok()) |
| 275 | .ok_or_else(|| { |
| 276 | ClientError::Protocol("409 without a valid X-Forge-Log-Size".into()) |
| 277 | })?; |
| 278 | Ok(LogAck::Resync(size)) |
| 279 | } |
| 280 | status if status.is_success() => Ok(LogAck::Accepted), |
| 281 | _ => Err(status_error(resp).await), |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | |
| 286 | pub async fn heartbeat( |
| 287 | &self, |
| 288 | job_id: &str, |
| 289 | job_token: &str, |
| 290 | ) -> Result<HeartbeatResponse, ClientError> { |
| 291 | self.heartbeat_with(job_id, job_token, None).await |
| 292 | } |
| 293 | |
| 294 | |
| 295 | pub async fn heartbeat_with( |
| 296 | &self, |
| 297 | job_id: &str, |
| 298 | job_token: &str, |
| 299 | concurrency: Option<usize>, |
| 300 | ) -> Result<HeartbeatResponse, ClientError> { |
| 301 | let mut req = self |
| 302 | .http |
| 303 | .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/heartbeat"))) |
| 304 | .bearer_auth(job_token) |
| 305 | .timeout(REQUEST_TIMEOUT); |
| 306 | if let Some(n) = concurrency { |
| 307 | req = req.header(CONCURRENCY_HEADER, n.to_string()); |
| 308 | } |
| 309 | req = req.header(BUILD_HEADER, forge_ci::build::display()); |
| 310 | json_or_error(req.send().await?).await |
| 311 | } |
| 312 | |
| 313 | |
| 314 | pub async fn upload_artifact( |
| 315 | &self, |
| 316 | job_id: &str, |
| 317 | job_token: &str, |
| 318 | name: &str, |
| 319 | path: &Path, |
| 320 | ) -> Result<(), ClientError> { |
| 321 | let file = tokio::fs::File::open(path).await?; |
| 322 | let len = file.metadata().await?.len(); |
| 323 | let stream = tokio_util::io::ReaderStream::new(file); |
| 324 | let resp = self |
| 325 | .http |
| 326 | .put(self.url(&format!("/api/v1/ci/jobs/{job_id}/artifacts/{name}"))) |
| 327 | .bearer_auth(job_token) |
| 328 | .header(CONTENT_LENGTH, len) |
| 329 | .body(reqwest::Body::wrap_stream(stream)) |
| 330 | .timeout(ARTIFACT_TIMEOUT) |
| 331 | .send() |
| 332 | .await?; |
| 333 | if resp.status().is_success() { |
| 334 | Ok(()) |
| 335 | } else { |
| 336 | Err(status_error(resp).await) |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | |
| 341 | pub async fn finish( |
| 342 | &self, |
| 343 | job_id: &str, |
| 344 | job_token: &str, |
| 345 | req: &FinishRequest, |
| 346 | ) -> Result<(), ClientError> { |
| 347 | let resp = self |
| 348 | .http |
| 349 | .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/finish"))) |
| 350 | .bearer_auth(job_token) |
| 351 | .json(req) |
| 352 | .timeout(REQUEST_TIMEOUT) |
| 353 | .send() |
| 354 | .await?; |
| 355 | if resp.status().is_success() { |
| 356 | Ok(()) |
| 357 | } else { |
| 358 | Err(status_error(resp).await) |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | |
| 363 | pub async fn requeue( |
| 364 | &self, |
| 365 | job_id: &str, |
| 366 | job_token: &str, |
| 367 | reason: &str, |
| 368 | ) -> Result<(), ClientError> { |
| 369 | let resp = self |
| 370 | .http |
| 371 | .post(self.url(&format!("/api/v1/ci/jobs/{job_id}/requeue"))) |
| 372 | .bearer_auth(job_token) |
| 373 | .json(&RequeueRequest { |
| 374 | reason: reason.to_owned(), |
| 375 | }) |
| 376 | .timeout(REQUEST_TIMEOUT) |
| 377 | .send() |
| 378 | .await?; |
| 379 | if resp.status().is_success() { |
| 380 | Ok(()) |
| 381 | } else { |
| 382 | Err(status_error(resp).await) |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | |
| 388 | fn advertised_sha256(headers: &HeaderMap) -> Option<String> { |
| 389 | headers |
| 390 | .get(HEADER_BINARY_SHA256)? |
| 391 | .to_str() |
| 392 | .ok() |
| 393 | .map(|v| v.trim().to_ascii_lowercase()) |
| 394 | .filter(|v| !v.is_empty()) |
| 395 | } |
| 396 | |
| 397 | |
| 398 | fn advertised_concurrency(headers: &HeaderMap) -> Option<u32> { |
| 399 | headers |
| 400 | .get(CONCURRENCY_HEADER)? |
| 401 | .to_str() |
| 402 | .ok()? |
| 403 | .trim() |
| 404 | .parse() |
| 405 | .ok() |
| 406 | } |
| 407 | |
| 408 | |
| 409 | fn advertised_restart(headers: &HeaderMap) -> Option<RestartMode> { |
| 410 | RestartMode::parse(headers.get(RESTART_HEADER)?.to_str().ok()?) |
| 411 | } |
| 412 | |
| 413 | |
| 414 | struct HostFacts { |
| 415 | cpus: Option<u32>, |
| 416 | memory_bytes: Option<u64>, |
| 417 | } |
| 418 | |
| 419 | fn header_text(headers: &HeaderMap, name: &str) -> Option<String> { |
| 420 | headers |
| 421 | .get(name) |
| 422 | .and_then(|v| v.to_str().ok()) |
| 423 | .map(|v| v.trim().to_owned()) |
| 424 | .filter(|v| !v.is_empty() && v.len() <= 32) |
| 425 | } |
| 426 | |
| 427 | fn host_facts() -> HostFacts { |
| 428 | let cpus = std::thread::available_parallelism() |
| 429 | .ok() |
| 430 | .and_then(|n| u32::try_from(n.get()).ok()); |
| 431 | let memory_bytes = std::fs::read_to_string("/proc/meminfo") |
| 432 | .ok() |
| 433 | .and_then(|text| parse_mem_total(&text)); |
| 434 | HostFacts { cpus, memory_bytes } |
| 435 | } |
| 436 | |
| 437 | |
| 438 | fn parse_mem_total(meminfo: &str) -> Option<u64> { |
| 439 | let line = meminfo.lines().find(|l| l.starts_with("MemTotal:"))?; |
| 440 | let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?; |
| 441 | kib.checked_mul(1024) |
| 442 | } |
| 443 | |
| 444 | async fn json_or_error<T: DeserializeOwned>(resp: reqwest::Response) -> Result<T, ClientError> { |
| 445 | if resp.status().is_success() { |
| 446 | Ok(resp.json().await?) |
| 447 | } else { |
| 448 | Err(status_error(resp).await) |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | async fn status_error(resp: reqwest::Response) -> ClientError { |
| 453 | let status = resp.status(); |
| 454 | let body: String = resp |
| 455 | .text() |
| 456 | .await |
| 457 | .unwrap_or_default() |
| 458 | .chars() |
| 459 | .take(512) |
| 460 | .collect(); |
| 461 | ClientError::Status { status, body } |
| 462 | } |
| 463 | |
| 464 | #[cfg(test)] |
| 465 | mod tests { |
| 466 | use super::*; |
| 467 | |
| 468 | #[test] |
| 469 | fn reads_mem_total_in_bytes() { |
| 470 | let text = "MemTotal: 16384 kB\nMemFree: 100 kB\n"; |
| 471 | assert_eq!(parse_mem_total(text), Some(16384 * 1024)); |
| 472 | assert_eq!(parse_mem_total("nothing"), None); |
| 473 | } |
| 474 | |
| 475 | #[test] |
| 476 | fn restart_header_must_name_a_mode() { |
| 477 | let mut headers = HeaderMap::new(); |
| 478 | assert_eq!(advertised_restart(&headers), None); |
| 479 | headers.insert(RESTART_HEADER, "drain".parse().unwrap()); |
| 480 | assert_eq!(advertised_restart(&headers), Some(RestartMode::Drain)); |
| 481 | headers.insert(RESTART_HEADER, "now".parse().unwrap()); |
| 482 | assert_eq!(advertised_restart(&headers), Some(RestartMode::Now)); |
| 483 | headers.insert(RESTART_HEADER, "later".parse().unwrap()); |
| 484 | assert_eq!(advertised_restart(&headers), None); |
| 485 | } |
| 486 | |
| 487 | #[test] |
| 488 | fn concurrency_header_must_be_a_number() { |
| 489 | let mut headers = HeaderMap::new(); |
| 490 | assert_eq!(advertised_concurrency(&headers), None); |
| 491 | headers.insert(CONCURRENCY_HEADER, "3".parse().unwrap()); |
| 492 | assert_eq!(advertised_concurrency(&headers), Some(3)); |
| 493 | headers.insert(CONCURRENCY_HEADER, "many".parse().unwrap()); |
| 494 | assert_eq!(advertised_concurrency(&headers), None); |
| 495 | } |
| 496 | } |