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