forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.5 MiB197fa34Tahinli1 month ago68 commits

api.rs1066 lines, 38.0 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/// How long a claim waits for work before answering 204.
46#[cfg(not(test))]
47const CLAIM_WAIT: std::time::Duration = std::time::Duration::from_secs(25);
48#[cfg(test)]
49const CLAIM_WAIT: std::time::Duration = std::time::Duration::from_millis(50);
50/// What the forge assumes a runner reserves for a job with no `memory`, when the runner did not say.
51const DEFAULT_RESERVE: u64 = 1 << 30;
52/// Longest runner name or label, in bytes.
53const MAX_NAME_BYTES: usize = 64;
54/// Most labels a runner may register.
55const MAX_LABELS: usize = 32;
56/// Text appended once when the log cap is reached.
57const TRUNCATED_MARKER: &[u8] = b"\n[log truncated]\n";
58const MIB: u64 = 1024 * 1024;
59
60/// Bearer token from the `Authorization` header, or `None`.
61fn bearer_token(headers: &HeaderMap) -> Option<&str> {
62 let value = headers.get(http::header::AUTHORIZATION)?.to_str().ok()?;
63 let (scheme, rest) = value.split_once(' ')?;
64 if !scheme.eq_ignore_ascii_case("bearer") {
65 return None;
66 }
67 let token = rest.trim();
68 (!token.is_empty()).then_some(token)
69}
70
71fn unauthorized() -> Refusal {
72 Box::new(api::error(
73 StatusCode::UNAUTHORIZED,
74 "authentication required",
75 ))
76}
77
78/// The runner behind the Bearer secret. Disabled runners get 403.
79async fn runner_from(state: &AppState, headers: &HeaderMap) -> Result<CiRunner, Refusal> {
80 let Some(secret) = bearer_token(headers) else {
81 return Err(unauthorized());
82 };
83 match state.store.runner_by_secret(secret).await {
84 Ok(Some(runner)) if runner.disabled => Err(Box::new(api::error(
85 StatusCode::FORBIDDEN,
86 "the runner is disabled",
87 ))),
88 Ok(Some(runner)) => {
89 crate::alerts::runner_seen(state, &runner.id).await;
90 Ok(runner)
91 }
92 Ok(None) => Err(unauthorized()),
93 Err(e) => Err(api::internal(e)),
94 }
95}
96
97/// The job behind the Bearer job token. Only Running jobs match, so a finished job gets 401.
98async fn job_from(state: &AppState, headers: &HeaderMap, job_id: &str) -> Result<CiJob, Refusal> {
99 let Some(token) = bearer_token(headers) else {
100 return Err(unauthorized());
101 };
102 match state.store.job_by_token(job_id, token).await {
103 Ok(Some(job)) => Ok(job),
104 Ok(None) => Err(unauthorized()),
105 Err(e) => Err(api::internal(e)),
106 }
107}
108
109/// Parses a JSON body of at most [`MAX_JSON_BODY`] bytes.
110async fn json_body<T: serde::de::DeserializeOwned>(body: Body) -> Result<T, Refusal> {
111 let bytes = api::read_body(body, MAX_JSON_BODY).await?;
112 serde_json::from_slice(&bytes).map_err(|e| {
113 Box::new(api::error(
114 StatusCode::BAD_REQUEST,
115 &format!("invalid JSON body: {e}"),
116 ))
117 })
118}
119
120fn valid_name(value: &str) -> bool {
121 !value.trim().is_empty() && value.len() <= MAX_NAME_BYTES && !value.contains(char::is_control)
122}
123
124/// `[A-Za-z0-9._+-]{1,128}`, and not starting with a dot.
125pub fn valid_artifact_name(name: &str) -> bool {
126 !name.is_empty()
127 && name.len() <= 128
128 && !name.starts_with('.')
129 && name
130 .bytes()
131 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'+' | b'-'))
132}
133
134// ---------------------------------------------------------------------------------------------
135// Registration and claims
136// ---------------------------------------------------------------------------------------------
137
138#[route(POST "/api/v1/ci/runners/register")]
139async fn register(cx: &Cx, body: Body) -> topcoat::Result<Response> {
140 let state = app_context::<AppState>(cx);
141 let request: RegisterRequest = match json_body(body).await {
142 Ok(request) => request,
143 Err(res) => return Ok(*res),
144 };
145 if !valid_name(&request.name) || request.labels.len() > MAX_LABELS {
146 return Ok(api::error(
147 StatusCode::UNPROCESSABLE_ENTITY,
148 "the runner name or labels are invalid",
149 ));
150 }
151 if request.labels.iter().any(|label| !valid_name(label)) {
152 return Ok(api::error(
153 StatusCode::UNPROCESSABLE_ENTITY,
154 "the runner name or labels are invalid",
155 ));
156 }
157 match state
158 .store
159 .register_runner(&request.token, request.name.trim(), &request.labels)
160 .await
161 {
162 Ok((runner, secret)) => {
163 let body = RegisterResponse {
164 runner_id: runner.id,
165 runner_secret: secret,
166 };
167 Ok(api::json(
168 StatusCode::CREATED,
169 &serde_json::to_value(&body).unwrap_or_default(),
170 ))
171 }
172 Err(CoreError::Invalid(_)) => Ok(api::error(
173 StatusCode::UNAUTHORIZED,
174 "the registration token is unknown, used or expired",
175 )),
176 Err(e) => Ok(*api::internal(e)),
177 }
178}
179
180#[route(POST "/api/v1/ci/runners/claim")]
181async fn claim(cx: &Cx, body: Body) -> topcoat::Result<Response> {
182 let state = app_context::<AppState>(cx);
183 // The labels in the request are ignored: the labels stored at registration are used.
184 let runner = match runner_from(state, headers(cx)).await {
185 Ok(runner) => runner,
186 Err(res) => return Ok(*res),
187 };
188 // What the runner says about itself. An older runner sends only labels, and a body that does
189 // not parse is not worth failing a claim over.
190 let request: ClaimRequest = match api::read_body(body, MAX_JSON_BODY).await {
191 Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(),
192 Err(_) => ClaimRequest::default(),
193 };
194 // An older runner sends no free memory, and then the oldest compatible job is handed out.
195 let offer = request.free_memory_bytes.map(|free| MemoryOffer {
196 free,
197 budget: request.memory_budget_bytes,
198 default_reserve: request.reserve_memory_bytes.unwrap_or(DEFAULT_RESERVE),
199 });
200 note_report(
201 state,
202 &runner.id,
203 &RunnerReport {
204 memory_budget: request.memory_budget_bytes,
205 memory_free: request.free_memory_bytes,
206 memory_reserve: request.reserve_memory_bytes,
207 concurrency: request.concurrency,
208 version: request.version.filter(|v| v.len() <= 64),
209 cpus: request.cpus,
210 memory_bytes: request.memory_bytes,
211 build: request.build.filter(|v| v.len() <= 64),
212 boot_id: request.boot_id.filter(|v| v.len() <= 64),
213 capabilities: request
214 .capabilities
215 .into_iter()
216 .filter(|c| !c.is_empty() && c.len() <= 32 && !c.contains(','))
217 .take(16)
218 .collect(),
219 },
220 )
221 .await;
222 let mut res = claim_work(state, &runner, offer).await?;
223 // The override can change during the long poll, so it is read at answer time.
224 set_concurrency_header(state, &runner.id, &mut res).await;
225 set_memory_headers(state, &runner.id, &mut res).await;
226 set_restart_header(state, &runner.id, &mut res).await;
227 // Advertises the binary sha256 when self-update is on and the runner asked for this target.
228 self_update::advertise(state, headers(cx), &mut res);
229 Ok(res)
230}
231
232/// Stores a runner's self report and wakes the admin pages when it changed something.
233async fn note_report(state: &AppState, runner_id: &str, report: &RunnerReport) {
234 match state.store.record_runner_report(runner_id, report).await {
235 Ok(true) => state.ci_live.bump_runners(),
236 Ok(false) => {}
237 Err(e) => tracing::warn!(error = %e, "ci: runner report not stored"),
238 }
239}
240
241/// Adds the admin's concurrency override to a claim answer. No header means no override.
242async fn set_concurrency_header(state: &AppState, runner_id: &str, res: &mut Response) {
243 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
244 return;
245 }
246 if let Ok(Some(n)) = state.store.runner_concurrency_override(runner_id).await
247 && let Ok(value) = HeaderValue::from_str(&n.to_string())
248 {
249 res.headers_mut().insert(CONCURRENCY_HEADER, value);
250 }
251}
252
253/// Adds the admin's memory budget and default reservation to a claim answer. No header means no
254/// override. An older runner ignores both.
255async fn set_memory_headers(state: &AppState, runner_id: &str, res: &mut Response) {
256 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
257 return;
258 }
259 for (key, header) in [
260 ("limits.memory_budget", MEMORY_BUDGET_HEADER),
261 ("limits.reserve_memory", RESERVE_MEMORY_HEADER),
262 ] {
263 if let Ok(Some(text)) = state.store.runner_field_override(runner_id, key).await
264 && let Ok(value) = HeaderValue::from_str(&text)
265 {
266 res.headers_mut().insert(header, value);
267 }
268 }
269}
270
271/// The restart an admin asked for, in the wire type. `None` when nothing is pending.
272async fn pending_restart(state: &AppState, runner_id: &str) -> Option<WireRestart> {
273 let mode = state.store.runner_restart(runner_id).await.ok().flatten()?;
274 WireRestart::parse(mode.as_str())
275}
276
277/// Adds the pending restart request to a claim answer. Sent on every answer until the runner
278/// comes back with a new boot id. An older runner ignores the header.
279async fn set_restart_header(state: &AppState, runner_id: &str, res: &mut Response) {
280 if !matches!(res.status(), StatusCode::OK | StatusCode::NO_CONTENT) {
281 return;
282 }
283 if let Some(mode) = pending_restart(state, runner_id).await {
284 res.headers_mut()
285 .insert(RESTART_HEADER, HeaderValue::from_static(mode.as_str()));
286 }
287}
288
289/// `GET` and `PUT /api/v1/ci/runners/config`. The runner reads the admin's overrides when it
290/// starts, applies them to its in-memory config, then reports its effective config here.
291#[route(GET "/api/v1/ci/runners/config")]
292async fn runner_config_get(cx: &Cx) -> topcoat::Result<Response> {
293 let state = app_context::<AppState>(cx);
294 let runner = match runner_from(state, headers(cx)).await {
295 Ok(runner) => runner,
296 Err(res) => return Ok(*res),
297 };
298 Ok(overrides_response(&runner))
299}
300
301#[route(PUT "/api/v1/ci/runners/config")]
302async fn runner_config_put(cx: &Cx, body: Body) -> topcoat::Result<Response> {
303 let state = app_context::<AppState>(cx);
304 let runner = match runner_from(state, headers(cx)).await {
305 Ok(runner) => runner,
306 Err(res) => return Ok(*res),
307 };
308 let report: RunnerConfigReport = match json_body(body).await {
309 Ok(report) => report,
310 Err(res) => return Ok(*res),
311 };
312 // Only known fields are kept, and the secret is never stored whatever the runner sent.
313 let mut config = report.config;
314 config.retain(|key, _| forge_core::ci::runner_field(key).is_some());
315 config.insert("runner_secret".into(), json!("<redacted>"));
316 match state
317 .store
318 .set_runner_reported_config(&runner.id, &config)
319 .await
320 {
321 Ok(true) => state.ci_live.bump_runners(),
322 Ok(false) => {}
323 Err(e) => return Ok(*api::internal(e)),
324 }
325 Ok(overrides_response(&runner))
326}
327
328fn overrides_response(runner: &CiRunner) -> Response {
329 let reply = RunnerConfigOverrides {
330 overrides: runner.config_overrides.clone(),
331 };
332 api::json(
333 StatusCode::OK,
334 &serde_json::to_value(reply).unwrap_or_default(),
335 )
336}
337
338async fn claim_work(
339 state: &AppState,
340 runner: &CiRunner,
341 offer: Option<MemoryOffer>,
342) -> topcoat::Result<Response> {
343 // Arm the wake-up before each attempt, so a job queued during the attempt is not missed.
344 // Producers use notify_waiters, which wakes every claimer, so a runner whose labels
345 // don't match a job re-arms and keeps waiting for the rest of CLAIM_WAIT.
346 let waker = state.ci_waker.clone();
347 let deadline = tokio::time::Instant::now() + CLAIM_WAIT;
348 loop {
349 let mut woken = std::pin::pin!(waker.notified());
350 woken.as_mut().enable();
351
352 // A runner that is to restart gets no new job. It is answered at once, so it sees the
353 // request without waiting out the long poll.
354 if matches!(state.store.runner_restart(&runner.id).await, Ok(Some(_))) {
355 return Ok(empty(StatusCode::NO_CONTENT));
356 }
357 match try_claim(state, runner, offer).await {
358 Ok(Some(assignment)) => return Ok(assignment_response(&assignment)),
359 Ok(None) => {}
360 Err(res) => return Ok(*res),
361 }
362 if tokio::time::timeout_at(deadline, woken.as_mut())
363 .await
364 .is_err()
365 {
366 return Ok(empty(StatusCode::NO_CONTENT));
367 }
368 }
369}
370
371/// The running binary, for a runner that updates itself. 404 unless self-update is enabled.
372#[route(GET "/api/v1/ci/runners/binary")]
373async fn runner_binary(cx: &Cx) -> topcoat::Result<Response> {
374 let state = app_context::<AppState>(cx);
375 if let Err(res) = runner_from(state, headers(cx)).await {
376 return Ok(*res);
377 }
378 if !state.config.self_update.enabled {
379 return Ok(api::error(StatusCode::NOT_FOUND, "self-update is disabled"));
380 }
381 match self_update::binary_response().await {
382 Ok(res) => Ok(res),
383 Err(e) => {
384 tracing::error!(error = %e, "ci: serving the runner binary failed");
385 Ok(api::error(
386 StatusCode::INTERNAL_SERVER_ERROR,
387 "the binary is unavailable",
388 ))
389 }
390 }
391}
392
393fn assignment_response(assignment: &JobAssignment) -> Response {
394 api::json(
395 StatusCode::OK,
396 &serde_json::to_value(assignment).unwrap_or_default(),
397 )
398}
399
400fn empty(status: StatusCode) -> Response {
401 let mut res = Response::new(topcoat::router::Body::empty());
402 *res.status_mut() = status;
403 res
404}
405
406/// One claim attempt. Builds the assignment, including the secrets the job may see.
407async fn try_claim(
408 state: &AppState,
409 runner: &CiRunner,
410 offer: Option<MemoryOffer>,
411) -> Result<Option<JobAssignment>, Refusal> {
412 let Some((job, run, job_token)) = state
413 .store
414 .claim_job_fitting(runner, offer)
415 .await
416 .map_err(api::internal)?
417 else {
418 return Ok(None);
419 };
420 state.ci_live.bump_job(&job.id);
421 state.ci_live.bump_run(&run.id);
422 state.ci_live.bump_repo(&run.repo_id);
423 state.ci_live.bump_runners();
424 let spec: JobSpec = serde_json::from_str(&job.spec_json).map_err(api::internal)?;
425 let repo = state
426 .store
427 .repo_by_id(&run.repo_id)
428 .await
429 .map_err(api::internal)?
430 .ok_or_else(|| api::internal("claimed job belongs to a missing repo"))?;
431
432 let secrets = if is_fork_run(state, &run).await? {
433 BTreeMap::new()
434 } else {
435 state
436 .store
437 .ci_secret_values(&run.repo_id, &spec.secrets)
438 .await
439 .map_err(api::internal)?
440 };
441
442 let (cache_key, cache_restore_keys) =
443 cache_scopes(state, &run, &repo.default_branch, &spec.cache).await?;
444
445 Ok(Some(JobAssignment {
446 job_id: job.id,
447 job_token,
448 repo: format!("{}/{}", repo.owner_name, repo.name),
449 clone_url: https_clone_url(&state.config, &repo.owner_name, &repo.name),
450 commit: run.commit_oid,
451 git_ref: run.git_ref,
452 job_name: job.name,
453 image: spec.image,
454 run: spec.run,
455 env: spec.env,
456 secrets,
457 artifacts: spec.artifacts,
458 timeout_minutes: spec.timeout_minutes,
459 network: spec.network,
460 cache: spec.cache,
461 cache_key,
462 cache_restore_keys,
463 memory_bytes: spec.memory,
464 }))
465}
466
467/// The cache scopes of a job's run. A job without `cache` gets none. A pull request run's base
468/// branch comes from its pull request record.
469async fn cache_scopes(
470 state: &AppState,
471 run: &CiRun,
472 default_branch: &str,
473 cache: &[String],
474) -> Result<(String, Vec<String>), Refusal> {
475 if cache.is_empty() {
476 return Ok((String::new(), Vec::new()));
477 }
478 let pull_base = match (run.trigger.as_str(), run.pull_number) {
479 ("pull_request", Some(number)) => state
480 .store
481 .pull_by_number(&run.repo_id, number)
482 .await
483 .map_err(api::internal)?
484 .map(|pull| pull.base_branch),
485 _ => None,
486 };
487 let scope = cache_scope(
488 &run.trigger,
489 &run.git_ref,
490 run.pull_number,
491 pull_base.as_deref(),
492 default_branch,
493 );
494 Ok(match scope {
495 Some(scope) => (scope.key, scope.restore_keys),
496 // A run whose scope cannot be derived gets no key, so the runner neither restores nor saves.
497 None => (String::new(), Vec::new()),
498 })
499}
500
501/// The cache scope a run may write, and the read-only scopes it may restore from.
502#[derive(Debug, Clone, PartialEq, Eq)]
503struct CacheScope {
504 key: String,
505 restore_keys: Vec<String>,
506}
507
508/// Derives the cache scopes of a run. Returns `None` when no scope can be derived.
509///
510/// Only pull request runs get `pr:` keys and only non-pull-request runs get `ref:` keys. The
511/// choice follows the run's trigger, never the ref name, so a pull request from a branch named
512/// `main` still writes `pr:N`. A pull request run reads its base branch's cache, a branch or tag
513/// run reads the default branch's cache, and both fall back to nothing else.
514fn cache_scope(
515 trigger: &str,
516 git_ref: &str,
517 pull_number: Option<i64>,
518 pull_base: Option<&str>,
519 default_branch: &str,
520) -> Option<CacheScope> {
521 let default_ref = format!("ref:refs/heads/{default_branch}");
522 match trigger {
523 "pull_request" => {
524 let number = pull_number?;
525 let mut restore_keys = Vec::new();
526 if let Some(base) = pull_base {
527 restore_keys.push(format!("ref:refs/heads/{base}"));
528 }
529 if pull_base != Some(default_branch) {
530 restore_keys.push(default_ref);
531 }
532 Some(CacheScope {
533 key: format!("pr:{number}"),
534 restore_keys,
535 })
536 }
537 "push" | "tag" | "manual" | "schedule" => {
538 let restore_keys = if git_ref == format!("refs/heads/{default_branch}") {
539 Vec::new()
540 } else {
541 vec![default_ref]
542 };
543 Some(CacheScope {
544 key: format!("ref:{git_ref}"),
545 restore_keys,
546 })
547 }
548 _ => None,
549 }
550}
551
552/// True for a pull-request run whose head is not this repo, or whose pull request is gone. Such
553/// runs get no secrets. Missing data counts as a fork, so the answer errs on the safe side.
554async fn is_fork_run(state: &AppState, run: &CiRun) -> Result<bool, Refusal> {
555 if run.trigger != "pull_request" {
556 return Ok(false);
557 }
558 let Some(number) = run.pull_number else {
559 return Ok(true);
560 };
561 match state
562 .store
563 .pull_by_number(&run.repo_id, number)
564 .await
565 .map_err(api::internal)?
566 {
567 Some(pull) => Ok(pull.head_repo_id.as_deref() != Some(run.repo_id.as_str())),
568 None => Ok(true),
569 }
570}
571
572// ---------------------------------------------------------------------------------------------
573// Heartbeat, logs and artifacts
574// ---------------------------------------------------------------------------------------------
575
576#[route(POST "/api/v1/ci/jobs/{job_id}/heartbeat")]
577async fn heartbeat(cx: &Cx) -> topcoat::Result<Response> {
578 let state = app_context::<AppState>(cx);
579 let job = match job_from(state, headers(cx), path_param::<JobId>(cx)).await {
580 Ok(job) => job,
581 Err(res) => return Ok(*res),
582 };
583 match state.store.heartbeat(&job.id).await {
584 Ok(cancel) => {
585 // The runner says its live concurrency, and the answer carries the admin's override.
586 // A runner at its limit does not claim, so this is how it learns about a change.
587 let mut concurrency = None;
588 let mut restart = None;
589 if let Some(runner_id) = job.runner_id.as_deref() {
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;