forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB3d53dfdTahinli1 month ago208 commits

api.rs1066 lines, 38.1 KiBHistoryRawDownload
1//! Runner and job API under `/api/v1/ci` (see docs/ci.md, Runner protocol).
2//!
3//! Runners authenticate with `Authorization: Bearer <runner secret>`. A job's routes take
4//! `Authorization: Bearer <job token>`, which `job_by_token` accepts only while the job is Running.
5//! The job token also works as a read-only git credential, see `git_http::job_token_read`.
6//!
7//! Every response is JSON except the empty 204 of an empty claim and the body of a log append.
8
9use forge_ci::config::JobSpec;
10use forge_ci::mask::Masker;
11use forge_ci::proto::{
12 BUILD_HEADER, CONCURRENCY_HEADER, ClaimRequest, FinishRequest, HeartbeatResponse,
13 JobAssignment, MEMORY_BUDGET_HEADER, Outcome, RESERVE_MEMORY_HEADER, RESTART_HEADER,
14 RegisterRequest, RegisterResponse, RequeueRequest, RestartMode as WireRestart,
15 RunnerConfigOverrides, RunnerConfigReport,
16};
17use forge_core::Error as CoreError;
18use forge_core::ci::{CiJob, CiRun, CiRunner, JobState, MemoryOffer, RunState, RunnerReport};
19use futures_util::StreamExt;
20use http::header::HeaderValue;
21use serde_json::json;
22use std::collections::BTreeMap;
23use topcoat::context::{Cx, app_context};
24use topcoat::router::request::headers;
25use topcoat::router::response::Response;
26use topcoat::router::{Body, HeaderMap, StatusCode, path_param, route};
27
28use crate::api::{self, Refusal};
29use crate::ci::{artifact_key, log_path};
30use crate::pages::repo::https_clone_url;
31use crate::self_update;
32use crate::state::AppState;
33
34path_param!(job_id);
35path_param!(artifact_name);
36
37/// Header carrying the byte offset of a log chunk.
38const LOG_OFFSET_HEADER: &str = "x-forge-log-offset";
39/// Header on a 409 log response carrying the size the server has.
40const LOG_SIZE_HEADER: &str = "x-forge-log-size";
41/// Largest log chunk, in bytes.
42const MAX_LOG_CHUNK: usize = 1024 * 1024;
43/// Largest JSON body on the runner routes, in bytes.
44const MAX_JSON_BODY: usize = 64 * 1024;
45/// What the forge assumes a runner reserves for a job with no `memory`, when the runner did not say.
46const DEFAULT_RESERVE: u64 = 1 << 30;
47/// Longest runner name or label, in bytes.
48const MAX_NAME_BYTES: usize = 64;
49/// Most labels a runner may register.
50const MAX_LABELS: usize = 32;
51/// Text appended once when the log cap is reached.
52const TRUNCATED_MARKER: &[u8] = b"\n[log truncated]\n";
53const MIB: u64 = 1024 * 1024;
54
55/// Bearer token from the `Authorization` header, or `None`.
56fn bearer_token(headers: &HeaderMap) -> Option<&str> {
57 let value = headers.get(http::header::AUTHORIZATION)?.to_str().ok()?;
58 let (scheme, rest) = value.split_once(' ')?;
59 if !scheme.eq_ignore_ascii_case("bearer") {
60 return None;
61 }
62 let token = rest.trim();
63 (!token.is_empty()).then_some(token)
64}
65
66fn unauthorized() -> Refusal {
67 Box::new(api::error(
68 StatusCode::UNAUTHORIZED,
69 "authentication required",
70 ))
71}
72
73/// The runner behind the Bearer secret. Disabled runners get 403.
74async fn runner_from(state: &AppState, headers: &HeaderMap) -> Result<CiRunner, Refusal> {
75 let Some(secret) = bearer_token(headers) else {
76 return Err(unauthorized());
77 };
78 match state.store.runner_by_secret(secret).await {
79 Ok(Some(runner)) if runner.disabled => Err(Box::new(api::error(
80 StatusCode::FORBIDDEN,
81 "the runner is disabled",
82 ))),
83 Ok(Some(runner)) => {
84 crate::alerts::runner_seen(state, &runner.id).await;
85 Ok(runner)
86 }
87 Ok(None) => Err(unauthorized()),
88 Err(e) => Err(api::internal(e)),
89 }
90}
91
92/// The job behind the Bearer job token. Only Running jobs match, so a finished job gets 401.
93async fn job_from(state: &AppState, headers: &HeaderMap, job_id: &str) -> Result<CiJob, Refusal> {
94 let Some(token) = bearer_token(headers) else {
95 return Err(unauthorized());
96 };
97 match state.store.job_by_token(job_id, token).await {
98 Ok(Some(job)) => Ok(job),
99 Ok(None) => Err(unauthorized()),
100 Err(e) => Err(api::internal(e)),
101 }
102}
103
104/// Parses a JSON body of at most [`MAX_JSON_BODY`] bytes.
105async fn json_body<T: serde::de::DeserializeOwned>(body: Body) -> Result<T, Refusal> {
106 let bytes = api::read_body(body, MAX_JSON_BODY).await?;
107 serde_json::from_slice(&bytes).map_err(|e| {
108 Box::new(api::error(
109 StatusCode::BAD_REQUEST,
110 &format!("invalid JSON body: {e}"),
111 ))
112 })
113}
114
115fn valid_name(value: &str) -> bool {
116 !value.trim().is_empty() && value.len() <= MAX_NAME_BYTES && !value.contains(char::is_control)
117}
118
119/// `[A-Za-z0-9._+-]{1,128}`, and not starting with a dot.
120pub fn valid_artifact_name(name: &str) -> bool {
121 !name.is_empty()
122 && name.len() <= 128
123 && !name.starts_with('.')
124 && name
125 .bytes()
126 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'+' | b'-'))
127}
128
129// ---------------------------------------------------------------------------------------------
130// Registration and claims
131// ---------------------------------------------------------------------------------------------
132
133#[route(POST "/api/v1/ci/runners/register")]
134async fn register(cx: &Cx, body: Body) -> topcoat::Result<Response> {
135 let state = app_context::<AppState>(cx);
136 let request: RegisterRequest = match json_body(body).await {
137 Ok(request) => request,
138 Err(res) => return Ok(*res),
139 };
140 if !valid_name(&request.name) || request.labels.len() > MAX_LABELS {
141 return Ok(api::error(
142 StatusCode::UNPROCESSABLE_ENTITY,
143 "the runner name or labels are invalid",
144 ));
145 }
146 if request.labels.iter().any(|label| !valid_name(label)) {
147 return Ok(api::error(
148 StatusCode::UNPROCESSABLE_ENTITY,
149 "the runner name or labels are invalid",
150 ));
151 }
152 match state
153 .store
154 .register_runner(&request.token, request.name.trim(), &request.labels)
155 .await
156 {
157 Ok((runner, secret)) => {
158 state.ci_live.bump_runners();
159 let body = RegisterResponse {
160 runner_id: runner.id,
161 runner_secret: secret,
162 };
163 Ok(api::json(
164 StatusCode::CREATED,
165 &serde_json::to_value(&body).unwrap_or_default(),
166 ))
167 }
168 Err(CoreError::Invalid(_)) => Ok(api::error(
169 StatusCode::UNAUTHORIZED,
170 "the registration token is unknown, used or expired",
171 )),
172 Err(e) => Ok(*api::internal(e)),
173 }
174}
175
176#[route(POST "/api/v1/ci/runners/claim")]
177async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> {
178 let state = app_context::<AppState>(cx);
179 // The labels in the request are ignored: the labels stored at registration are used.
180 let runner = match runner_from(state, headers(cx)).await {
181 Ok(runner) => runner,
182 Err(res) => return Ok(*res),
183 };
184 // What the runner says about itself. An older runner sends only labels, and a body that does
185 // not parse is not worth failing a claim over.
186 let request: ClaimRequest = match api::read_body(body, MAX_JSON_BODY).await {
187 Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(),
188 Err(_) => ClaimRequest::default(),
189 };
190 // An older runner sends no free memory, and then the oldest compatible job is handed out.
191 let offer = request.free_memory_bytes.map(|free| MemoryOffer {
192 free,
193 budget: request.memory_budget_bytes,
194 default_reserve: request.reserve_memory_bytes.unwrap_or(DEFAULT_RESERVE),
195 });
196 note_report(
197 state,
198 &runner.id,
199 &RunnerReport {
200 memory_budget: request.memory_budget_bytes,
201 memory_free: request.free_memory_bytes,
202 memory_reserve: request.reserve_memory_bytes,
203 concurrency: request.concurrency,
204 version: request.version.filter(|v| v.len() <= 64),
205 cpus: request.cpus,
206 memory_bytes: request.memory_bytes,
207 build: request.build.filter(|v| v.len() <= 64),
208 boot_id: request.boot_id.filter(|v| v.len() <= 64),
209 capabilities: request
210 .capabilities
211 .into_iter()
212 .filter(|c| !c.is_empty() && c.len() <= 32 && !c.contains(','))
213 .take(16)
214 .collect(),
215 },
216 )
217 .await;
218 let mut res = claim_work(state, &runner, offer).await?;
219 // The override can change during the long poll, so it is read at answer time.
220 set_concurrency_header(state, &runner.id, &mut res).await;
221 set_memory_headers(state, &runner.id, &mut res).await;
222 set_restart_header(state, &runner.id, &mut res).await;
223 // Advertises the binary sha256 when self-update is on and the runner asked for this target.
224 self_update::advertise(state, headers(cx), &mut res);
225 Ok(res)
226}
227
228/// Stores a runner's self report and wakes the admin pages when it changed something.
229async fn note_report(state: &AppState, runner_id: &str, report: &RunnerReport) {
230 match state.store.record_runner_report(runner_id, report).await {
231 Ok(true) => state.ci_live.bump_runners(),
232 Ok(false) => {}
233 Err(e) => tracing::warn!(error = %e, "ci: runner report not stored"),
234 }
235}
236
237/// Adds the admin's concurrency override to a claim answer. No header means no override.
238async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Response) {
239 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
240 return;
241 }
242 if let Ok(Some(n)) = state.store.runner_concurrency_override(runner_id).await
243 && let Ok(value) = HeaderValue::from_str(&n.to_string())
244 {
245 res.headers_mut().insert(CONCURRENCY_HEADER, value);
246 }
247}
248
249/// Adds the admin's memory budget and default reservation to a claim answer. No header means no
250/// override. An older runner ignores both.
251async fn set_memory_headers(state: &AppState, runner_id: &str, res: &mut Response) {
252 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
253 return;
254 }
255 for (key, header) in [
256 ("limits.memory_budget", MEMORY_BUDGET_HEADER),
257 ("limits.reserve_memory", RESERVE_MEMORY_HEADER),
258 ] {
259 if let Ok(Some(text)) = state.store.runner_field_override(runner_id, key).await
260 && let Ok(value) = HeaderValue::from_str(&text)
261 {
262 res.headers_mut().insert(header, value);
263 }
264 }
265}
266
267/// The restart an admin asked for, in the wire type. `None` when nothing is pending.
268async fn pending_restart(state: &AppState, runner_id: &str) -> Option<WireRestart> {
269 let mode = state.store.runner_restart(runner_id).await.ok().flatten()?;
270 WireRestart::parse(mode.as_str())
271}
272
273/// Adds the pending restart request to a claim answer. Sent on every answer until the runner
274/// comes back with a new boot id. An older runner ignores the header.
275async fn set_restart_header(state: &AppState, runner_id: &str, res: &mut Response) {
276 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
277 return;
278 }
279 if let Some(mode) = pending_restart(state, runner_id).await {
280 res.headers_mut()
281 .insert(RESTART_HEADER, HeaderValue::from_static(mode.as_str()));
282 }
283}
284
285/// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it
286/// starts, applies them to its in-memory config, then reports its effective config here.
287#[route(GET "/api/v1/ci/runners/config")]
288async fn runner_config_get(cx: &Cx) -> topcoat::Result<Response> {
289 let state = app_context::<AppState>(cx);
290 let runner = match runner_from(state, headers(cx)).await {
291 Ok(runner) => runner,
292 Err(res) => return Ok(*res),
293 };
294 Ok(overrides_response(&runner))
295}
296
297#[route(PUT "/api/v1/ci/runners/config")]
298async fn runner_config_put(cx: &Cx, body: Body) -> topcoat::Result<Response> {
299 let state = app_context::<AppState>(cx);
300 let runner = match runner_from(state, headers(cx)).await {
301 Ok(runner) => runner,
302 Err(res) => return Ok(*res),
303 };
304 let report: RunnerConfigReport = match json_body(body).await {
305 Ok(report) => report,
306 Err(res) => return Ok(*res),
307 };
308 // Only known fields are kept, and the secret is never stored whatever the runner sent.
309 let mut config = report.config;
310 config.retain(|key, _| forge_core::ci::runner_field(key).is_some());
311 config.insert("runner_secret".into(), json!("<redacted>"));
312 match state
313 .store
314 .set_runner_reported_config(&runner.id, &config)
315 .await
316 {
317 Ok(true) => state.ci_live.bump_runners(),
318 Ok(false) => {}
319 Err(e) => return Ok(*api::internal(e)),
320 }
321 Ok(overrides_response(&runner))
322}
323
324fn overrides_response(runner: &CiRunner) -> Response {
325 let reply = RunnerConfigOverrides {
326 overrides: runner.config_overrides.clone(),
327 };
328 api::json(
329 StatusCode::OK,
330 &serde_json::to_value(reply).unwrap_or_default(),
331 )
332}
333
334async fn claim_work(
335 state: &AppState,
336 runner: &CiRunner,
337 offer: Option<MemoryOffer>,
338) -> topcoat::Result<Response> {
339 // Arm the wake-up before each attempt, so a job queued during the attempt is not missed.
340 // Producers use notify_waiters, which wakes every claimer, so a runner whose labels
341 // don't match a job re-arms and keeps waiting for the rest of the claim wait.
342 let waker = state.ci_waker.clone();
343 let wait = std::time::Duration::from_millis(state.config.ci.claim_wait_ms);
344 let deadline = tokio::time::Instant::now() + wait;
345 loop {
346 let mut woken = std::pin::pin!(waker.notified());
347 woken.as_mut().enable();
348
349 // A runner that is to restart gets no new job. It is answered at once, so it sees the
350 // request without waiting out the long poll.
351 if matches!(state.store.runner_restart(&runner.id).await, Ok(Some(_))) {
352 return Ok(empty(StatusCode::NO_CONTENT));
353 }
354 match try_claim(state, runner, offer).await {
355 Ok(Some(assignment)) => return Ok(assignment_response(&assignment)),
356 Ok(None) => {}
357 Err(res) => return Ok(*res),
358 }
359 if tokio::time::timeout_at(deadline, woken.as_mut())
360 .await
361 .is_err()
362 {
363 return Ok(empty(StatusCode::NO_CONTENT));
364 }
365 }
366}
367
368/// The running binary, for a runner that updates itself. 404 unless self-update is enabled.
369#[route(GET "/api/v1/ci/runners/binary")]
370async fn runner_binary(cx: &Cx) -> topcoat::Result<Response> {
371 let state = app_context::<AppState>(cx);
372 if let Err(res) = runner_from(state, headers(cx)).await {
373 return Ok(*res);
374 }
375 if !state.config.self_update.enabled {
376 return Ok(api::error(StatusCode::NOT_FOUND, "self-update is disabled"));
377 }
378 match self_update::binary_response().await {
379 Ok(res) => Ok(res),
380 Err(e) => {
381 tracing::error!(error = %e, "ci: serving the runner binary failed");
382 Ok(api::error(
383 StatusCode::INTERNAL_SERVER_ERROR,
384 "the binary is unavailable",
385 ))
386 }
387 }
388}
389
390fn assignment_response(assignment: &JobAssignment) -> Response {
391 api::json(
392 StatusCode::OK,
393 &serde_json::to_value(assignment).unwrap_or_default(),
394 )
395}
396
397fn empty(status: StatusCode) -> Response {
398 let mut res = Response::new(topcoat::router::Body::empty());
399 *res.status_mut() = status;
400 res
401}
402
403/// One claim attempt. Builds the assignment, including the secrets the job may see.
404async fn try_claim(
405 state: &AppState,
406 runner: &CiRunner,
407 offer: Option<MemoryOffer>,
408) -> Result<Option<JobAssignment>, Refusal> {
409 let Some((job, run, job_token)) = state
410 .store
411 .claim_job_fitting(runner, offer)
412 .await
413 .map_err(api::internal)?
414 else {
415 return Ok(None);
416 };
417 state.ci_live.bump_job(&job.id);
418 state.ci_live.bump_run(&run.id);
419 state.ci_live.bump_repo(&run.repo_id);
420 state.ci_live.bump_runners();
421 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
422 let repo = state
423 .store
424 .repo_by_id(&run.repo_id)
425 .await
426 .map_err(api::internal)?
427 .ok_or_else(|| api::internal("claimed job belongs to a missing repo"))?;
428
429 let secrets = if is_fork_run(state, &run).await? {
430 BTreeMap::new()
431 } else {
432 state
433 .store
434 .ci_secret_values(&run.repo_id, &spec.secrets)
435 .await
436 .map_err(api::internal)?
437 };
438
439 let (cache_key, cache_restore_keys) =
440 cache_scopes(state, &run, &repo.default_branch, &spec.cache).await?;
441
442 Ok(Some(JobAssignment {
443 job_id: job.id,
444 job_token,
445 repo: format!("{}/{}", repo.owner_name, repo.name),
446 clone_url: https_clone_url(&state.config, &repo.owner_name, &repo.name),
447 commit: run.commit_oid,
448 git_ref: run.git_ref,
449 job_name: job.name,
450 image: spec.image,
451 run: spec.run,
452 env: spec.env,
453 secrets,
454 artifacts: spec.artifacts,
455 timeout_minutes: spec.timeout_minutes,
456 network: spec.network,
457 cache: spec.cache,
458 cache_key,
459 cache_restore_keys,
460 memory_bytes: spec.memory,
461 }))
462}
463
464/// The cache scopes of a job's run. A job without `cache` gets none. A pull request run's base
465/// branch comes from its pull request record.
466async fn cache_scopes(
467 state: &AppState,
468 run: &CiRun,
469 default_branch: &str,
470 cache: &[String],
471) -> Result<(String, Vec<String>), Refusal> {
472 if cache.is_empty() {
473 return Ok((String::new(), Vec::new()));
474 }
475 let pull_base = match (run.trigger.as_str(), run.pull_number) {
476 ("pull_request", Some(number)) => state
477 .store
478 .pull_by_number(&run.repo_id, number)
479 .await
480 .map_err(api::internal)?
481 .map(|pull| pull.base_branch),
482 _ => None,
483 };
484 let scope = cache_scope(
485 &run.trigger,
486 &run.git_ref,
487 run.pull_number,
488 pull_base.as_deref(),
489 default_branch,
490 );
491 Ok(match scope {
492 Some(scope) => (scope.key, scope.restore_keys),
493 // A run whose scope cannot be derived gets no key, so the runner neither restores nor saves.
494 None => (String::new(), Vec::new()),
495 })
496}
497
498/// The cache scope a run may write, and the read-only scopes it may restore from.
499#[derive(Debug, Clone, PartialEq, Eq)]
500struct CacheScope {
501 key: String,
502 restore_keys: Vec<String>,
503}
504
505/// Derives the cache scopes of a run. Returns `None` when no scope can be derived.
506///
507/// Only pull request runs get `pr:` keys and only non-pull-request runs get `ref:` keys. The
508/// choice follows the run's trigger, never the ref name, so a pull request from a branch named
509/// `main` still writes `pr:N`. A pull request run reads its base branch's cache, a branch or tag
510/// run reads the default branch's cache, and both fall back to nothing else.
511fn cache_scope(
512 trigger: &str,
513 git_ref: &str,
514 pull_number: Option<i64>,
515 pull_base: Option<&str>,
516 default_branch: &str,
517) -> Option<CacheScope> {
518 let default_ref = format!("ref:refs/heads/{default_branch}");
519 match trigger {
520 "pull_request" => {
521 let number = pull_number?;
522 let mut restore_keys = Vec::new();
523 if let Some(base) = pull_base {
524 restore_keys.push(format!("ref:refs/heads/{base}"));
525 }
526 if pull_base != Some(default_branch) {
527 restore_keys.push(default_ref);
528 }
529 Some(CacheScope {
530 key: format!("pr:{number}"),
531 restore_keys,
532 })
533 }
534 "push" | "tag" | "manual" | "schedule" => {
535 let restore_keys = if git_ref == format!("refs/heads/{default_branch}") {
536 Vec::new()
537 } else {
538 vec![default_ref]
539 };
540 Some(CacheScope {
541 key: format!("ref:{git_ref}"),
542 restore_keys,
543 })
544 }
545 _ => None,
546 }
547}
548
549/// True for a pull-request run whose head is not this repo, or whose pull request is gone. Such
550/// runs get no secrets. Missing data counts as a fork, so the answer errs on the safe side.
551async fn is_fork_run(state: &AppState, run: &CiRun) -> Result<bool, Refusal> {
552 if run.trigger != "pull_request" {
553 return Ok(false);
554 }
555 let Some(number) = run.pull_number else {
556 return Ok(true);
557 };
558 match state
559 .store
560 .pull_by_number(&run.repo_id, number)
561 .await
562 .map_err(api::internal)?
563 {
564 Some(pull) => Ok(pull.head_repo_id.as_deref() != Some(run.repo_id.as_str())),
565 None => Ok(true),
566 }
567}
568
569// ---------------------------------------------------------------------------------------------
570// Heartbeat, logs and artifacts
571// ---------------------------------------------------------------------------------------------
572
573#[route(POST "/api/v1/ci/jobs/{job_id}/heartbeat")]
574async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> {
575 let state = app_context::<AppState>(cx);
576 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
577 Ok(job) => job,
578 Err(res) => return Ok(*res),
579 };
580 match state.store.heartbeat(&job.id).await {
581 Ok(cancel) => {
582 // The runner says its live concurrency, and the answer carries the admin's override.
583 // A runner at its limit does not claim, so this is how it learns about a change.
584 let mut concurrency = None;
585 let mut restart = None;
586 if let Some(runner_id) = job.runner_id.as_deref() {
587 if let Err(e) = state.store.touch_runner(runner_id).await {
588 tracing::warn!(error = %e, "ci: runner last-seen not stored");
589 }
590 let said = headers(cx)
591 .get(CONCURRENCY_HEADER)
592 .and_then(|v| v.to_str().ok())
593 .and_then(|v| v.trim().parse::<u32>().ok());
594 note_report(
595 state,
596 runner_id,
597 &RunnerReport {
598 concurrency: said,
599 build: headers(cx)
600 .get(BUILD_HEADER)
601 .and_then(|v| v.to_str().ok())
602 .filter(|v| v.len() <= 64)
603 .map(str::to_owned),
604 ..RunnerReport::default()
605 },
606 )
607 .await;
608 concurrency = state
609 .store
610 .runner_concurrency_override(runner_id)
611 .await
612 .ok()
613 .flatten();
614 restart = pending_restart(state, runner_id).await;
615 }
616 Ok(api::json(
617 StatusCode::OK,
618 &serde_json::to_value(HeartbeatResponse {
619 cancel,
620 concurrency,
621 restart,
622 })
623 .unwrap_or_default(),
624 ))
625 }
626 Err(e) => Ok(*api::internal(e)),
627 }
628}
629
630/// Outcome of a log append.
631enum LogWrite {
632 /// The chunk is stored (or was dropped by the cap); the size is the new byte count.
633 Stored(u64),
634 /// This exact chunk was already stored: a retry. The size is unchanged.
635 Duplicate(u64),
636 /// The offset does not match the stored size.
637 Mismatch(u64),
638}
639
640#[route(POST "/api/v1/ci/jobs/{job_id}/logs")]
641async fn append_log(cx: &Cx, body: Body) -> topcoat::Result<Response> {
642 let state = app_context::<AppState>(cx);
643 let headers = headers(cx);
644 let job = match job_from(state, headers, path_param::<JobId>(cx)).await {
645 Ok(job) => job,
646 Err(res) => return Ok(*res),
647 };
648 let Some(offset) = headers
649 .get(LOG_OFFSET_HEADER)
650 .and_then(|value| value.to_str().ok())
651 .and_then(|value| value.parse::<u64>().ok())
652 else {
653 return Ok(api::error(
654 StatusCode::BAD_REQUEST,
655 "X-Forge-Log-Offset must be a byte offset",
656 ));
657 };
658 let chunk = match api::read_body(body, MAX_LOG_CHUNK).await {
659 Ok(chunk) => chunk,
660 Err(res) => return Ok(*res),
661 };
662 match write_log(state, &job, offset, &chunk).await {
663 Ok(LogWrite::Stored(size) | LogWrite::Duplicate(size)) => {
664 Ok(api::json(StatusCode::OK, &json!({ "size": size })))
665 }
666 Ok(LogWrite::Mismatch(size)) => {
667 let mut res = api::error(StatusCode::CONFLICT, "the log offset does not match");
668 res.headers_mut().insert(
669 http::HeaderName::from_static(LOG_SIZE_HEADER),
670 HeaderValue::from(size),
671 );
672 Ok(res)
673 }
674 Err(res) => Ok(*res),
675 }
676}
677
678/// Appends one chunk of raw log bytes. Offsets count the raw bytes the runner sent, which is
679/// `job.log_bytes`; the file holds the masked text, so its length may differ.
680async fn write_log(
681 state: &AppState,
682 job: &CiJob,
683 offset: u64,
684 chunk: &[u8],
685) -> Result<LogWrite, Refusal> {
686 let size = u64::try_from(job.log_bytes).unwrap_or(0);
687 let len = chunk.len() as u64;
688 if offset != size {
689 return Ok(if offset.checked_add(len) == Some(size) {
690 LogWrite::Duplicate(size)
691 } else {
692 LogWrite::Mismatch(size)
693 });
694 }
695 if chunk.is_empty() {
696 return Ok(LogWrite::Stored(size));
697 }
698
699 let masked = mask_for_job(state, job, chunk).await?;
700 let path = log_path(&state.config.data_dir, &job.id);
701 store_log_bytes(state, &path, &masked).await?;
702 state
703 .store
704 .add_log_bytes(&job.id, len as i64)
705 .await
706 .map_err(api::internal)?;
707 state.ci_live.bump_job(&job.id);
708 // The run page shows the last log lines, so its streams wake too. The page debounces.
709 state.ci_live.bump_run(&job.run_id);
710 if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await {
711 state.ci_live.bump_repo(&run.repo_id);
712 }
713 Ok(LogWrite::Stored(size + len))
714}
715
716/// Masks a chunk with the values of the job's secrets. The chunk is masked on its own, so a
717/// secret split across two requests is masked by the runner, which holds back the boundary.
718async fn mask_for_job(state: &AppState, job: &CiJob, chunk: &[u8]) -> Result<Vec<u8>, Refusal> {
719 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
720 if spec.secrets.is_empty() {
721 return Ok(chunk.to_vec());
722 }
723 let Some(run) = state
724 .store
725 .run_by_id(&job.run_id)
726 .await
727 .map_err(api::internal)?
728 else {
729 return Err(api::internal("log for a job with no run"));
730 };
731 let values = state
732 .store
733 .ci_secret_values(&run.repo_id, &spec.secrets)
734 .await
735 .map_err(api::internal)?;
736 let masker = Masker::new(values.into_values());
737 let mut stream = masker.stream();
738 let mut out = stream.push(chunk);
739 out.extend(stream.finish());
740 Ok(out)
741}
742
743/// The bytes of `masked` that may be appended to a log of `current` bytes under a `cap`. Once the
744/// log reaches the cap nothing more is kept. When the new bytes do not fit, the part that does is
745/// kept and the marker follows it, so the file ends at exactly `cap` bytes.
746pub fn fit_to_cap(current: u64, cap: u64, masked: &[u8]) -> Vec<u8> {
747 if current >= cap {
748 return Vec::new();
749 }
750 let data_cap = cap.saturating_sub(TRUNCATED_MARKER.len() as u64);
751 let room = data_cap.saturating_sub(current);
752 if masked.len() as u64 <= room {
753 return masked.to_vec();
754 }
755 let mut out = masked[..room as usize].to_vec();
756 out.extend_from_slice(TRUNCATED_MARKER);
757 out
758}
759
760/// Appends masked bytes to the log file, stopping at the size cap with one marker line.
761async fn store_log_bytes(
762 state: &AppState,
763 path: &std::path::Path,
764 masked: &[u8],
765) -> Result<(), Refusal> {
766 use tokio::io::AsyncWriteExt;
767
768 let cap = state.live().ci.max_log_mb.saturating_mul(MIB);
769 let current = match tokio::fs::metadata(path).await {
770 Ok(meta) => meta.len(),
771 Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
772 Err(e) => return Err(api::internal(e)),
773 };
774 let out = fit_to_cap(current, cap, masked);
775 if out.is_empty() {
776 return Ok(());
777 }
778
779 if let Some(parent) = path.parent() {
780 tokio::fs::create_dir_all(parent)
781 .await
782 .map_err(api::internal)?;
783 }
784 let mut file = tokio::fs::OpenOptions::new()
785 .create(true)
786 .append(true)
787 .open(path)
788 .await
789 .map_err(api::internal)?;
790 file.write_all(&out).await.map_err(api::internal)?;
791 file.flush().await.map_err(api::internal)?;
792 Ok(())
793}
794
795#[route(PUT "/api/v1/ci/jobs/{job_id}/artifacts/{artifact_name}")]
796async fn upload_artifact(cx: &Cx, body: Body) -> topcoat::Result<Response> {
797 let state = app_context::<AppState>(cx);
798 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
799 Ok(job) => job,
800 Err(res) => return Ok(*res),
801 };
802 let name = path_param::<ArtifactName>(cx);
803 if !valid_artifact_name(name) {
804 return Ok(api::error(
805 StatusCode::UNPROCESSABLE_ENTITY,
806 "the artifact name must be 1 to 128 of A-Z a-z 0-9 . _ + - and not start with a dot",
807 ));
808 }
809 match upload(state, &job, name, body).await {
810 Ok(artifact_id) => Ok(api::json(
811 StatusCode::CREATED,
812 &json!({ "id": artifact_id, "name": name }),
813 )),
814 Err(res) => Ok(*res),
815 }
816}
817
818/// Streams the body to a temporary blob, then records the artifact and moves the blob to its
819/// final key `ci/<artifact id>`. The id is only known once the row exists.
820async fn upload(state: &AppState, job: &CiJob, name: &str, body: Body) -> Result<String, Refusal> {
821 let max_artifacts = state.live().ci.max_artifacts_per_job;
822 let existing = state
823 .store
824 .list_artifacts(&job.id)
825 .await
826 .map_err(api::internal)?;
827 if existing.len() as u64 >= u64::from(max_artifacts) {
828 return Err(Box::new(api::error(
829 StatusCode::CONFLICT,
830 "the job has too many artifacts",
831 )));
832 }
833 if existing.iter().any(|artifact| artifact.name == name) {
834 return Err(Box::new(api::error(
835 StatusCode::CONFLICT,
836 "an artifact with this name already exists",
837 )));
838 }
839
840 let max_bytes = state.live().ci.max_artifact_mb.saturating_mul(MIB);
841 let temp_key = format!("ci/tmp/{}", ulid::Ulid::generate());
842 let mut writer = state
843 .blobs
844 .begin(&temp_key, max_bytes)
845 .await
846 .map_err(api::internal)?;
847 let mut stream = std::pin::pin!(body.into_data_stream());
848 while let Some(next) = stream.next().await {
849 let outcome = match next {
850 Ok(chunk) => writer.push(&chunk).await.map_err(|e| (e, false)),
851 Err(_) => Err((CoreError::Invalid("upload interrupted".into()), true)),
852 };
853 if let Err((e, interrupted)) = outcome {
854 writer.abort().await;
855 return Err(upload_failure(e, interrupted));
856 }
857 }
858 let (size, sha256) = match writer.finish().await {
859 Ok(done) => done,
860 Err(e) => {
861 discard_temp(state, &temp_key).await;
862 return Err(api::internal(e));
863 }
864 };
865
866 let artifact = match state
867 .store
868 .add_artifact(&job.id, name, size as i64, &sha256)
869 .await
870 {
871 Ok(artifact) => artifact,
872 Err(e) => {
873 discard_temp(state, &temp_key).await;
874 return Err(match e {
875 CoreError::Invalid(message) => Box::new(api::error(StatusCode::CONFLICT, &message)),
876 other => api::internal(other),
877 });
878 }
879 };
880 let final_key = artifact_key(&artifact.id);
881 if let Err(e) = state.blobs.rename(&temp_key, &final_key).await {
882 discard_temp(state, &temp_key).await;
883 return Err(api::internal(e));
884 }
885 Ok(artifact.id)
886}
887
888/// Removes a temporary blob. A failure is logged; the blob is unreachable either way.
889async fn discard_temp(state: &AppState, key: &str) {
890 if let Err(e) = state.blobs.delete(key).await {
891 tracing::error!(error = %e, "ci: could not remove a temporary artifact blob");
892 }
893}
894
895fn upload_failure(e: CoreError, interrupted: bool) -> Refusal {
896 match e {
897 CoreError::Invalid(_) if !interrupted => Box::new(api::error(
898 StatusCode::PAYLOAD_TOO_LARGE,
899 "the artifact is larger than the upload limit",
900 )),
901 CoreError::Invalid(message) => Box::new(api::error(StatusCode::BAD_REQUEST, &message)),
902 other => api::internal(other),
903 }
904}
905
906// ---------------------------------------------------------------------------------------------
907// Finish
908// ---------------------------------------------------------------------------------------------
909
910#[route(POST "/api/v1/ci/jobs/{job_id}/finish")]
911async fn finish(cx: &Cx, body: Body) -> topcoat::Result<Response> {
912 let state = app_context::<AppState>(cx);
913 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
914 Ok(job) => job,
915 Err(res) => return Ok(*res),
916 };
917 let request: FinishRequest = match json_body(body).await {
918 Ok(request) => request,
919 Err(res) => return Ok(*res),
920 };
921 let state_after = match request.outcome {
922 Outcome::Success => JobState::Success,
923 Outcome::Failure => JobState::Failure,
924 Outcome::Cancelled => JobState::Cancelled,
925 Outcome::Error => JobState::Error,
926 };
927 match finish_job(state, &job, state_after, &request).await {
928 Ok(state_name) => Ok(api::json(StatusCode::OK, &json!({ "state": state_name }))),
929 Err(res) => Ok(*res),
930 }
931}
932
933#[route(POST "/api/v1/ci/jobs/{job_id}/requeue")]
934async fn requeue(cx: &Cx, body: Body) -> topcoat::Result<Response> {
935 let state = app_context::<AppState>(cx);
936 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
937 Ok(job) => job,
938 Err(res) => return Ok(*res),
939 };
940 let request: RequeueRequest = match json_body(body).await {
941 Ok(request) => request,
942 Err(res) => return Ok(*res),
943 };
944 match state.store.requeue_job(&job.id).await {
945 Ok(true) => {}
946 Ok(false) => {
947 return Ok(api::error(StatusCode::CONFLICT, "the job is not running"));
948 }
949 Err(e) => return Ok(*api::internal(e)),
950 }
951 // The next attempt starts from a clean log with one line saying why.
952 let path = log_path(&state.config.data_dir, &job.id);
953 let reason = request.reason.replace(['\r', '\n'], " ");
954 let note = format!("requeued: {reason}. It will start again\n");
955 if let Some(parent) = path.parent()
956 && let Err(e) = tokio::fs::create_dir_all(parent).await
957 {
958 tracing::warn!(error = %e, "ci: log directory not created");
959 }
960 if let Err(e) = tokio::fs::write(&path, note).await {
961 tracing::warn!(error = %e, "ci: requeue log note not written");
962 }
963 state.ci_live.bump_job(&job.id);
964 state.ci_live.bump_run(&job.run_id);
965 state.ci_live.bump_runners();
966 if let Ok(Some(run)) = state.store.run_by_id(&job.run_id).await {
967 state.ci_live.bump_repo(&run.repo_id);
968 if let Ok(Some(fresh)) = state.store.job_by_id(&job.id).await {
969 crate::ci::sync_status(state, &run, &fresh).await;
970 }
971 }
972 state.ci_waker.notify_waiters();
973 Ok(api::json(StatusCode::OK, &json!({ "state": "queued" })))
974}
975
976/// Finishes the job, then syncs the statuses of the job and of every job whose state changed
977/// (skipped or queued by this finish). Wakes the claimers when something was queued, and the
978/// watchers of every job and run that changed.
979async fn finish_job(
980 state: &AppState,
981 job: &CiJob,
982 outcome: JobState,
983 request: &FinishRequest,
984) -> Result<&'static str, Refusal> {
985 let before: BTreeMap<String, JobState> = state
986 .store
987 .jobs_for_run(&job.run_id)
988 .await
989 .map_err(api::internal)?
990 .into_iter()
991 .map(|other| (other.id, other.state))
992 .collect();
993 let exit_code = request.exit_code.map(i64::from);
994 // The runner read the job cgroup's OOM counters. A count without the flag is believed too.
995 let oom_kills = match (request.oom_killed, request.oom_kills) {
996 (Some(false), _) => 0,
997 (_, Some(n)) => n.max(1),
998 (Some(true), None) => 1,
999 (None, None) => 0,
1000 };
1001 let run = state
1002 .store
1003 .finish_job(&job.id, outcome, exit_code, request.message.as_deref())
1004 .await
1005 .map_err(api::internal)?;
1006
1007 if oom_kills > 0
1008 && let Err(e) = state.store.set_job_oom_kills(&job.id, oom_kills).await
1009 {
1010 tracing::warn!(error = %e, "ci: oom kills not stored");
1011 }
1012 let mut queued = false;
1013 let mut any_changed = false;
1014 for other in state
1015 .store
1016 .jobs_for_run(&job.run_id)
1017 .await
1018 .map_err(api::internal)?
1019 {
1020 let changed = before.get(&other.id) != Some(&other.state);
1021 if changed {
1022 any_changed = true;
1023 if other.state.is_terminal() {
1024 state.ci_live.close_job(&other.id);
1025 } else {
1026 state.ci_live.bump_job(&other.id);
1027 }
1028 }
1029 if other.id == job.id
1030 || (changed && matches!(other.state, JobState::Skipped | JobState::Queued))
1031 {
1032 queued |= other.state == JobState::Queued;
1033 crate::ci::sync_status(state, &run, &other).await;
1034 }
1035 }
1036 state.ci_live.bump_runners();
1037 if matches!(outcome, JobState::Failure | JobState::Error) {
1038 crate::alerts::job_ended(
1039 state,
1040 job,
1041 exit_code,
1042 request.message.as_deref(),
1043 oom_kills > 0,
1044 )
1045 .await;
1046 }
1047 if any_changed {
1048 state.ci_live.bump_run(&run.id);
1049 state.ci_live.bump_repo(&run.repo_id);
1050 }
1051 if queued {
1052 state.ci_waker.notify_waiters();
1053 }
1054 // A run that just went green may deploy the forge itself.
1055 self_update::maybe_deploy(state, &run).await;
1056 // A tag run that went green may publish a release. The request does not wait for it.
1057 if run.state == RunState::Success {
1058 let (state, run) = (state.clone(), run.clone());
1059 tokio::spawn(async move { crate::ci::release::on_run_finished(&state, &run).await });
1060 }
1061 Ok(run.state.as_str())
1062}
1063
1064#[cfg(test)]
1065#[path = "api_tests.rs"]
1066mod tests;