| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
use crate::api::ApiError; |
| 6 |
use crate::db::{self, flow as fdb}; |
| 7 |
use crate::repos::RepoName; |
| 8 |
use crate::Shared; |
| 9 |
use axum::extract::{Path, State}; |
| 10 |
use axum::http::{HeaderMap, StatusCode}; |
| 11 |
use axum::response::{IntoResponse, Response}; |
| 12 |
use axum::Json; |
| 13 |
use flow_core::api::{Claim, ClaimRequest, Finish, LogBatch, MAX_RECORDS, MAX_RECORD_TEXT}; |
| 14 |
use flow_core::{Pipeline, PIPELINE_PATH}; |
| 15 |
use oxy_core::hash::ChangeHash; |
| 16 |
|
| 17 |
|
| 18 |
pub const JOB_TOKEN_PREFIX: &str = "flowjob_"; |
| 19 |
|
| 20 |
pub const JOB_TOKEN_MAX_AGE_MS: i64 = 2 * 3600 * 1000; |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
pub async fn on_push(app: &Shared, row: &db::repos::RepoRow, bookmark: &str, state: &str, heads: &[ChangeHash], actor: &str) { |
| 25 |
if bookmark.starts_with("tags/") || heads.is_empty() || !app.config.flow.allows(&row.owner, &row.name) { |
| 26 |
return; |
| 27 |
} |
| 28 |
let Some(repo) = RepoName::new(&row.owner, &row.name) else { return }; |
| 29 |
let h = heads.to_vec(); |
| 30 |
let text = app |
| 31 |
.repos |
| 32 |
.read(&repo, move |r, cache| { |
| 33 |
let loaded = cache.load(r, &h)?; |
| 34 |
Ok(match loaded.snapshot.files.get(PIPELINE_PATH).map(|f| &f.content) { |
| 35 |
Some(oxy_core::state::FileContent::Text { bytes, .. }) => Some(String::from_utf8_lossy(bytes).into_owned()), |
| 36 |
_ => None, |
| 37 |
}) |
| 38 |
}) |
| 39 |
.await; |
| 40 |
let text = match text { |
| 41 |
Ok(Some(t)) => t, |
| 42 |
Ok(None) => return, |
| 43 |
Err(e) => { |
| 44 |
tracing::warn!("flow: reading the pipeline of {repo}: {e}"); |
| 45 |
return; |
| 46 |
} |
| 47 |
}; |
| 48 |
let mut hex: Vec<String> = heads.iter().map(|h| h.to_hex()).collect(); |
| 49 |
hex.sort(); |
| 50 |
let heads_s = hex.join("+"); |
| 51 |
let base = db::flow::NewRun { repo_id: row.id, bookmark, state, heads: &heads_s, pipeline_hash: "", actor, error: None }; |
| 52 |
let result = match Pipeline::parse(&text) { |
| 53 |
Err(problems) => { |
| 54 |
let msg = problems.to_string(); |
| 55 |
db::flow::create_run(&app.db, db::flow::NewRun { error: Some(&msg), ..base }, &[]).await |
| 56 |
} |
| 57 |
Ok(p) => { |
| 58 |
let depths = p.depths(); |
| 59 |
let jobs: Vec<fdb::NewJob> = p |
| 60 |
.order() |
| 61 |
.into_iter() |
| 62 |
.map(|j| { |
| 63 |
let sb = &p.sandboxes[&j.sandbox]; |
| 64 |
fdb::NewJob { |
| 65 |
name: j.name.clone(), |
| 66 |
depth: depths[j.name.as_str()] as i64, |
| 67 |
depends: j.depends_on.clone(), |
| 68 |
spec: serde_json::to_string(j).unwrap_or_default(), |
| 69 |
sandbox: serde_json::to_string(sb).unwrap_or_default(), |
| 70 |
runtime: sb.runtime.as_str().into(), |
| 71 |
} |
| 72 |
}) |
| 73 |
.collect(); |
| 74 |
let hash = hex::encode(p.hash()); |
| 75 |
let id = db::flow::create_run(&app.db, db::flow::NewRun { pipeline_hash: &hash, ..base }, &jobs).await; |
| 76 |
if let Ok(id) = id { |
| 77 |
for j in &jobs { |
| 78 |
report_check(app, row, state, id, &j.name, "queued", "waiting for a runner").await; |
| 79 |
} |
| 80 |
} |
| 81 |
id |
| 82 |
} |
| 83 |
}; |
| 84 |
if let Err(e) = result { |
| 85 |
tracing::warn!("flow: recording a run of {repo}: {e}"); |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
async fn report_check(app: &Shared, row: &db::repos::RepoRow, state: &str, run_id: i64, job: &str, status: &str, summary: &str) { |
| 90 |
let url = format!("{}/{}/{}/flow/{run_id}", app.config.base_url(), row.owner, row.name); |
| 91 |
let name = format!("flow/{job}"); |
| 92 |
let c = db::hooks::upsert_check( |
| 93 |
&app.db, |
| 94 |
row.id, |
| 95 |
db::hooks::CheckReport { state, name: &name, status, summary, url: &url, reporter: None, seal: "" }, |
| 96 |
) |
| 97 |
.await; |
| 98 |
if let Ok(c) = c { |
| 99 |
let api = crate::api::check_of(&c); |
| 100 |
app.events.proposal(row.id, hub_api::ProposalEvent { number: 0, kind: "check".into(), check: Some(api.clone()) }); |
| 101 |
crate::hooks::emit(app, row, "check", "flow", serde_json::json!({ "check": api })).await; |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
|
| 106 |
fn check_status(job_status: &str) -> &'static str { |
| 107 |
match job_status { |
| 108 |
"queued" => "queued", |
| 109 |
"running" => "running", |
| 110 |
"passed" => "passed", |
| 111 |
"skipped" => "skipped", |
| 112 |
_ => "failed", |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
fn runner_auth(app: &Shared, headers: &HeaderMap) -> Result<(), ApiError> { |
| 117 |
let Some(t) = oxy_server::bearer_token(headers) else { |
| 118 |
return Err(ApiError(StatusCode::UNAUTHORIZED, "a runner token is required".into())); |
| 119 |
}; |
| 120 |
if app.config.flow.runner_tokens.iter().any(|x| crate::auth::mac_equal(x, t)) { |
| 121 |
Ok(()) |
| 122 |
} else { |
| 123 |
Err(ApiError(StatusCode::UNAUTHORIZED, "not a runner token".into())) |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
|
| 128 |
pub async fn claim(State(app): State<Shared>, headers: HeaderMap, Json(req): Json<ClaimRequest>) -> Result<Response, ApiError> { |
| 129 |
runner_auth(&app, &headers)?; |
| 130 |
let runner: String = req.runner.chars().filter(|c| !c.is_control()).take(64).collect(); |
| 131 |
let secret = format!("{JOB_TOKEN_PREFIX}{}", crate::auth::random_hex(32)); |
| 132 |
let room = fdb::Room { memory_mib: req.free_memory_mib, cpus: req.free_cpus }; |
| 133 |
let Some(job) = fdb::claim_within(&app.db, &req.runtimes, &runner, &crate::auth::token_hash(&secret), room).await? else { |
| 134 |
return Ok(StatusCode::NO_CONTENT.into_response()); |
| 135 |
}; |
| 136 |
let run = fdb::run_by_id(&app.db, job.run_id).await?.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "no such run".into()))?; |
| 137 |
let row = |
| 138 |
db::repos::get_by_id(&app.db, run.repo_id).await?.ok_or_else(|| ApiError(StatusCode::NOT_FOUND, "no such repository".into()))?; |
| 139 |
report_check(&app, &row, &run.state, run.id, &job.name, "running", &format!("running on {runner}")).await; |
| 140 |
let bad = |e: serde_json::Error| ApiError(StatusCode::INTERNAL_SERVER_ERROR, format!("stored job: {e}")); |
| 141 |
let claim = Claim { |
| 142 |
job_id: job.id, |
| 143 |
run_id: run.id, |
| 144 |
repo: format!("{}/{}", row.owner, row.name), |
| 145 |
clone_url: format!("{}/{}/{}", app.config.base_url(), row.owner, row.name), |
| 146 |
token: secret, |
| 147 |
heads: run.head_list().into_iter().map(String::from).collect(), |
| 148 |
pipeline_hash: run.pipeline_hash.clone(), |
| 149 |
job: serde_json::from_str(&job.spec).map_err(bad)?, |
| 150 |
sandbox: serde_json::from_str(&job.sandbox).map_err(bad)?, |
| 151 |
timeout_s: app.config.flow.job_timeout_minutes.max(1) * 60, |
| 152 |
subrepos: vec![], |
| 153 |
}; |
| 154 |
let mut claim = claim; |
| 155 |
let (inputs, ids) = subrepo_inputs(&app, &row, &run).await; |
| 156 |
if !ids.is_empty() { |
| 157 |
fdb::set_also_read(&app.db, job.id, &ids).await?; |
| 158 |
} |
| 159 |
claim.subrepos = inputs; |
| 160 |
Ok(Json(claim).into_response()) |
| 161 |
} |
| 162 |
|
| 163 |
|
| 164 |
async fn pins_in( |
| 165 |
app: &Shared, |
| 166 |
name: crate::repos::RepoName, |
| 167 |
heads: Vec<oxy_core::hash::ChangeHash>, |
| 168 |
) -> Vec<(String, [u8; 16], Vec<oxy_core::hash::ChangeHash>)> { |
| 169 |
app.repos |
| 170 |
.read(&name, move |repo, cache| { |
| 171 |
let loaded = cache.load(repo, &heads)?; |
| 172 |
let mut out = Vec::new(); |
| 173 |
for (path, f) in &loaded.snapshot.files { |
| 174 |
if f.kind != oxy_core::objects::NodeKind::Subrepo { |
| 175 |
continue; |
| 176 |
} |
| 177 |
if let oxy_core::state::FileContent::Opaque { blobs } = &f.content { |
| 178 |
if let Some(b) = blobs.first() { |
| 179 |
if let Ok(oxy_core::subrepo::Pin::Oxy { repo: id, heads, .. }) = repo |
| 180 |
.read_blob(b) |
| 181 |
.map_err(crate::repos::RepoError::Oxy) |
| 182 |
.and_then(|bytes| oxy_core::subrepo::Pin::decode(&bytes).map_err(|e| crate::repos::RepoError::Oxy(e.into()))) |
| 183 |
{ |
| 184 |
out.push((path.clone(), id, heads)); |
| 185 |
} |
| 186 |
} |
| 187 |
} |
| 188 |
} |
| 189 |
Ok(out) |
| 190 |
}) |
| 191 |
.await |
| 192 |
.unwrap_or_default() |
| 193 |
} |
| 194 |
|
| 195 |
|
| 196 |
const MAX_SUBREPO_DEPTH: usize = 3; |
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
async fn subrepo_inputs(app: &Shared, row: &db::repos::RepoRow, run: &fdb::Run) -> (Vec<flow_core::api::SubrepoInput>, Vec<i64>) { |
| 204 |
let Some(name) = crate::repos::RepoName::new(&row.owner, &row.name) else { return (vec![], vec![]) }; |
| 205 |
let heads: Vec<oxy_core::hash::ChangeHash> = run.head_list().into_iter().filter_map(oxy_core::hash::ChangeHash::from_hex).collect(); |
| 206 |
let pusher = db::accounts::account_by_name(&app.db, &run.actor).await.ok().flatten(); |
| 207 |
let rows = db::repos::list(&app.db).await.unwrap_or_default(); |
| 208 |
let mut inputs = Vec::new(); |
| 209 |
let mut ids = Vec::new(); |
| 210 |
|
| 211 |
let mut queue = std::collections::VecDeque::from([(String::new(), name, heads, 0usize)]); |
| 212 |
while let Some((prefix, name, heads, depth)) = queue.pop_front() { |
| 213 |
if depth == MAX_SUBREPO_DEPTH { |
| 214 |
continue; |
| 215 |
} |
| 216 |
for (path, id, pinned) in pins_in(app, name, heads).await { |
| 217 |
let path = if prefix.is_empty() { path } else { format!("{prefix}/{path}") }; |
| 218 |
for other in &rows { |
| 219 |
let Some(other_name) = crate::repos::RepoName::new(&other.owner, &other.name) else { continue }; |
| 220 |
let matches = app.repos.read(&other_name, move |r, _| Ok(r.id().ok() == Some(id))).await.unwrap_or(false); |
| 221 |
if !matches { |
| 222 |
continue; |
| 223 |
} |
| 224 |
let role = crate::auth::roles::role_for(&app.db, pusher.as_ref(), other).await.ok().flatten(); |
| 225 |
if crate::auth::roles::allows(role, crate::auth::Access::Read) { |
| 226 |
inputs.push(flow_core::api::SubrepoInput { |
| 227 |
path: path.clone(), |
| 228 |
repo: format!("{}/{}", other.owner, other.name), |
| 229 |
clone_url: format!("{}/{}/{}", app.config.base_url(), other.owner, other.name), |
| 230 |
heads: pinned.iter().map(|h| h.to_hex()).collect(), |
| 231 |
}); |
| 232 |
if !ids.contains(&other.id) { |
| 233 |
ids.push(other.id); |
| 234 |
} |
| 235 |
queue.push_back((path.clone(), other_name, pinned.clone(), depth + 1)); |
| 236 |
} |
| 237 |
break; |
| 238 |
} |
| 239 |
} |
| 240 |
} |
| 241 |
(inputs, ids) |
| 242 |
} |
| 243 |
|
| 244 |
async fn running_job(app: &Shared, id: i64) -> Result<fdb::Job, ApiError> { |
| 245 |
match fdb::job(&app.db, id).await? { |
| 246 |
Some(j) if j.status == "running" => Ok(j), |
| 247 |
Some(_) => Err(ApiError(StatusCode::CONFLICT, "this job is not running".into())), |
| 248 |
None => Err(ApiError(StatusCode::NOT_FOUND, "no such job".into())), |
| 249 |
} |
| 250 |
} |
| 251 |
|
| 252 |
|
| 253 |
pub async fn log( |
| 254 |
State(app): State<Shared>, |
| 255 |
headers: HeaderMap, |
| 256 |
Path(id): Path<i64>, |
| 257 |
Json(mut batch): Json<LogBatch>, |
| 258 |
) -> Result<StatusCode, ApiError> { |
| 259 |
runner_auth(&app, &headers)?; |
| 260 |
let job = running_job(&app, id).await?; |
| 261 |
for r in &mut batch.records { |
| 262 |
if r.text.len() > MAX_RECORD_TEXT { |
| 263 |
let mut cut = MAX_RECORD_TEXT; |
| 264 |
while !r.text.is_char_boundary(cut) { |
| 265 |
cut -= 1; |
| 266 |
} |
| 267 |
r.text.truncate(cut); |
| 268 |
} |
| 269 |
if !matches!(r.stream.as_str(), "out" | "err" | "console" | "flow") { |
| 270 |
r.stream = "console".into(); |
| 271 |
} |
| 272 |
} |
| 273 |
let kept = fdb::append_log(&app.db, job.id, &batch.records, MAX_RECORDS as i64).await?; |
| 274 |
if kept < batch.records.len() && job.log_count < MAX_RECORDS as i64 { |
| 275 |
tracing::info!("flow: job {} reached the log limit", job.id); |
| 276 |
} |
| 277 |
Ok(StatusCode::NO_CONTENT) |
| 278 |
} |
| 279 |
|
| 280 |
|
| 281 |
pub async fn finish( |
| 282 |
State(app): State<Shared>, |
| 283 |
headers: HeaderMap, |
| 284 |
Path(id): Path<i64>, |
| 285 |
Json(f): Json<Finish>, |
| 286 |
) -> Result<StatusCode, ApiError> { |
| 287 |
runner_auth(&app, &headers)?; |
| 288 |
let job = running_job(&app, id).await?; |
| 289 |
let status = match (f.exit_code, &f.error) { |
| 290 |
(Some(0), None) => "passed", |
| 291 |
(Some(_), _) => "failed", |
| 292 |
(None, _) => "error", |
| 293 |
}; |
| 294 |
let (receipt, receipt_hash) = match &f.receipt { |
| 295 |
Some(r) if r.job_name == job.name && Some(r.exit_code as i32) == f.exit_code => { |
| 296 |
(serde_json::to_string(r).unwrap_or_default(), hex::encode(r.hash())) |
| 297 |
} |
| 298 |
Some(_) => return Err(ApiError(StatusCode::BAD_REQUEST, "the receipt does not match the job".into())), |
| 299 |
None => (String::new(), String::new()), |
| 300 |
}; |
| 301 |
let error = f.error.clone().unwrap_or_default(); |
| 302 |
let changed = fdb::finish( |
| 303 |
&app.db, |
| 304 |
job.id, |
| 305 |
fdb::Outcome { status, exit_code: f.exit_code.map(i64::from), error: &error, receipt: &receipt, receipt_hash: &receipt_hash }, |
| 306 |
) |
| 307 |
.await?; |
| 308 |
if let Some(run) = fdb::run_by_id(&app.db, job.run_id).await? { |
| 309 |
if let Some(row) = db::repos::get_by_id(&app.db, run.repo_id).await? { |
| 310 |
for j in changed { |
| 311 |
let summary = match j.status.as_str() { |
| 312 |
"passed" => format!("passed in {}", duration(&j)), |
| 313 |
"failed" => format!("exit {} after {}", j.exit_code.unwrap_or(-1), duration(&j)), |
| 314 |
"skipped" => "skipped: a dependency did not pass".into(), |
| 315 |
_ => format!("could not run: {}", j.error), |
| 316 |
}; |
| 317 |
report_check(&app, &row, &run.state, run.id, &j.name, check_status(&j.status), &summary).await; |
| 318 |
} |
| 319 |
} |
| 320 |
} |
| 321 |
Ok(StatusCode::NO_CONTENT) |
| 322 |
} |
| 323 |
|
| 324 |
|
| 325 |
pub fn duration(j: &fdb::Job) -> String { |
| 326 |
match (j.started_ms, j.finished_ms) { |
| 327 |
(Some(a), Some(b)) => human_ms(b - a), |
| 328 |
(Some(a), None) => human_ms(db::now_ms() - a), |
| 329 |
_ => "–".into(), |
| 330 |
} |
| 331 |
} |
| 332 |
|
| 333 |
pub fn human_ms(ms: i64) -> String { |
| 334 |
let ms = ms.max(0); |
| 335 |
if ms < 1000 { |
| 336 |
format!("{ms} ms") |
| 337 |
} else if ms < 60_000 { |
| 338 |
format!("{:.1} s", ms as f64 / 1000.0) |
| 339 |
} else { |
| 340 |
format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000) |
| 341 |
} |
| 342 |
} |