forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.7 MiBb00f3f4Tahinli1 month ago147 commits

client.rs496 lines, 16.9 KiBHistoryRawDownload
1//! HTTP client for the forge runner API (contract section 4).
2//!
3//! Runner calls (register, claim) authenticate with the runner secret. Job calls (logs,
4//! heartbeat, artifacts, finish) authenticate with the per-job token.
5
6use std::path::Path;
7use std::time::Duration;
8
9use 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};
15use reqwest::StatusCode;
16use reqwest::header::{CONTENT_LENGTH, HeaderMap};
17use serde::de::DeserializeOwned;
18use sha2::{Digest, Sha256};
19use tokio::io::AsyncWriteExt;
20
21/// The claim long-poll is 25s on the forge side, so 35s leaves room for the response.
22pub const CLAIM_TIMEOUT: Duration = Duration::from_secs(35);
23const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
24const LOG_TIMEOUT: Duration = Duration::from_secs(60);
25const ARTIFACT_TIMEOUT: Duration = Duration::from_secs(60 * 60);
26const BINARY_TIMEOUT: Duration = Duration::from_secs(10 * 60);
27const HEADER_LOG_OFFSET: &str = "X-Forge-Log-Offset";
28const HEADER_LOG_SIZE: &str = "X-Forge-Log-Size";
29/// Sent on every claim: `<ARCH>-<OS>` of this runner, for example `x86_64-linux`.
30const HEADER_RUNNER_TARGET: &str = "Forge-Runner-Target";
31/// On a claim response: the sha256 (hex) of the forge's own binary, if the forge advertises one.
32const HEADER_BINARY_SHA256: &str = "Forge-Binary-Sha256";
33/// `GET`: the forge's binary, for a runner that is updating itself.
34const BINARY_PATH: &str = "/api/v1/ci/runners/binary";
35const CONFIG_PATH: &str = "/api/v1/ci/runners/config";
36
37/// Errors from talking to the forge.
38#[derive(Debug, thiserror::Error)]
39pub 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/// The forge's answer to a log chunk.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum LogAck {
53 /// The chunk was stored (or was already stored, which is an idempotent retry).
54 Accepted,
55 /// The forge holds a different number of bytes. The runner must continue from this size.
56 Resync(u64),
57}
58
59/// The forge's answer to a claim.
60#[derive(Clone, Debug)]
61pub struct ClaimReply {
62 /// The job assigned to this runner, or `None` when there is nothing to run (204).
63 pub job: Option<JobAssignment>,
64 /// The sha256 (lowercase hex) of the forge's binary, when the response advertises one.
65 pub binary_sha256: Option<String>,
66 /// The concurrency an admin set in the web UI. `None` means no override.
67 pub concurrency: Option<u32>,
68 /// A restart an admin asked for, from the `Forge-Runner-Restart` header.
69 pub restart: Option<RestartMode>,
70 /// The memory budget an admin set (`6g`). `None` means no override.
71 pub memory_budget: Option<String>,
72 /// The default reservation an admin set (`1g`). `None` means no override.
73 pub reserve_memory: Option<String>,
74}
75
76/// What a claim tells the forge about the runner's memory.
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub struct MemoryClaim {
79 /// Budget minus running reservations: the forge hands out only a job that fits.
80 pub free: u64,
81 pub budget: u64,
82 /// What a job without `memory` reserves.
83 pub reserve: u64,
84}
85
86/// A client for one forge base URL.
87#[derive(Clone, Debug)]
88pub struct ForgeClient {
89 http: reqwest::Client,
90 base: String,
91}
92
93impl ForgeClient {
94 /// Builds a client for `base_url`, for example `https://forge.example`.
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 /// `POST /api/v1/ci/runners/register`.
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 /// `POST /api/v1/ci/runners/claim`. A 204 means nothing to run, and the reply has no job.
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 /// Like [`ForgeClient::claim`], and also reports the runner's live `concurrency` and its host
132 /// facts (version, CPUs, memory) for the forge's admin page.
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 /// `GET /api/v1/ci/runners/config`: the overrides an admin set for this runner.
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 /// `PUT /api/v1/ci/runners/config`: reports the runner's effective config (secrets redacted).
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 /// `GET /api/v1/ci/runners/binary`. Streams the forge's binary into `dest` and returns the
223 /// sha256 (lowercase hex) of the bytes written. The caller checks it against the advertised
224 /// value and syncs the file.
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 /// `POST /api/v1/ci/jobs/{id}/logs` with the byte offset of `body` in the job log.
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 /// `POST /api/v1/ci/jobs/{id}/heartbeat`.
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 /// Like [`ForgeClient::heartbeat`], and also tells the forge the runner's live `concurrency`.
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 /// `PUT /api/v1/ci/jobs/{id}/artifacts/{name}`, streaming the file from disk.
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 /// `POST /api/v1/ci/jobs/{id}/finish`.
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 /// `POST /api/v1/ci/jobs/{id}/requeue`. The forge queues the job again, keeping its place.
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/// The `Forge-Binary-Sha256` header, trimmed and lowercased. An empty value counts as absent.
388fn 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/// The `Forge-Runner-Concurrency` header, when it holds a number.
398fn 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/// The `Forge-Runner-Restart` header, when it holds a mode this runner knows.
409fn advertised_restart(headers: &HeaderMap) -> Option<RestartMode> {
410 RestartMode::parse(headers.get(RESTART_HEADER)?.to_str().ok()?)
411}
412
413/// Cheap facts about the host that help an admin size the runner's concurrency.
414struct HostFacts {
415 cpus: Option<u32>,
416 memory_bytes: Option<u64>,
417}
418
419fn 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
427fn 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/// `MemTotal` of `/proc/meminfo`, in bytes. The file reports kibibytes.
438fn 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
444async 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
452async 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)]
465mod 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}