mod native_step;
use crate::artifact::{self};
use crate::artifact_io;
use crate::context::ExecContext;
use crate::dag::{self, ExecutionTask};
use crate::expr::{self, Ctx, Status};
use crate::frozen::FrozenPlan;
use crate::matrix;
use crate::os_legs;
use crate::plan::{self, Plan, Unit};
use crate::setup::{
self, PreparedHow, PreparedReceipt, PreparedSetup, PreparedStep, SetupRecipe, TemplateContext,
};
use crate::step_executor::{ScriptPipe, StepExecutor, StepRequest};
use crate::task::{self, combine, outcome_of, JobOutcome, JobStatus, TaskInputs, TaskResult};
use crate::workflow::{Job, Service, Step, Workflow};
use anyhow::{anyhow, bail, Context, Result};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "result", content = "reason", rename_all = "lowercase")]
pub enum Outcome {
Pass,
Fail,
Skip(String),
Error(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StepResult {
pub label: String,
#[serde(flatten)]
pub outcome: Outcome,
#[serde(skip_serializing_if = "Option::is_none")]
pub exit: Option<i32>,
pub secs: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub log: Option<PathBuf>,
#[serde(skip_serializing_if = "Option::is_none")]
pub note: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobResult {
pub workflow: String,
pub job: String,
pub display: String,
#[serde(flatten)]
pub outcome: Outcome,
pub secs: f64,
pub steps: Vec<StepResult>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub cancelled: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub time: Option<JobTime>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub build_cache: Option<crate::build_cache::JobCache>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub os_note: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct JobTime {
pub work_secs: f64,
pub wait_lock_secs: f64,
pub wait_slot_secs: f64,
pub wait_queue_secs: f64,
pub wait_parallel_secs: f64,
#[serde(default)]
pub requested_at_ms: u64,
#[serde(default)]
pub started_at_ms: u64,
#[serde(default)]
pub finished_at_ms: u64,
}
pub fn now_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
}
#[derive(Debug, Clone, Copy, Default)]
struct UnitWait {
lock: f64,
parallel: f64,
requested_at_ms: u64,
}
impl UnitWait {
fn total(self) -> f64 {
self.lock + self.parallel
}
}
fn charge(jobs: &mut [JobResult], w: UnitWait) {
if w.requested_at_ms > 0 {
for t in jobs.iter_mut().filter_map(|j| j.time.as_mut()) {
t.requested_at_ms = match t.requested_at_ms {
0 => w.requested_at_ms,
r => r.min(w.requested_at_ms),
};
}
}
if w.total() <= 0.0 {
return;
}
let at = jobs.iter().position(|j| j.time.is_some()).unwrap_or(0);
if let Some(j) = jobs.get_mut(at) {
let secs = j.secs;
let t = j.time.get_or_insert_with(|| JobTime {
work_secs: secs,
..JobTime::default()
});
t.wait_lock_secs += w.lock;
t.wait_parallel_secs += w.parallel;
if t.requested_at_ms == 0 {
t.requested_at_ms = w.requested_at_ms;
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct UnitResult {
#[serde(skip_serializing_if = "Option::is_none")]
pub unit: Option<usize>,
pub workflow: String,
pub jobs: Vec<JobResult>,
pub waited_secs: f64,
#[serde(skip_serializing_if = "Option::is_none")]
pub copy_secs: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cached: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub outcomes: Vec<JobOutcome>,
}
pub struct Opts {
pub parallel: usize,
pub traffic_controller: Option<PathBuf>,
pub executor: Option<Arc<dyn crate::step_executor::StepExecutor>>,
pub portool: Option<PathBuf>,
pub containers: usize,
pub job_timeout_min: f64,
pub keep: bool,
pub trash: PathBuf,
pub all_os_legs: bool,
}
#[derive(Clone, Debug)]
pub struct Workspace {
pub root: PathBuf,
pub repo_root: PathBuf,
pub run_dir: PathBuf,
pub tools: PathBuf,
pub lock_file: PathBuf,
}
pub struct Runner<'a> {
selected: Option<(
crate::driver::dispatch::Selection,
crate::driver::PortableFacts,
)>,
pinned: Option<(
&'a crate::source_execute::PinnedExecution<'a>,
&'a crate::source_execute::PinnedWorkspace,
&'a dyn crate::source_execute::PinnedWorkspaceProvider,
)>,
pub ctx: &'a ExecContext,
pub fp: &'a FrozenPlan,
pub plan: Plan,
pub repo_root: PathBuf,
pub wt: PathBuf,
pub run_dir: PathBuf,
pub tools: PathBuf,
pub lock_file: PathBuf,
pub slug: String,
pub opts: Opts,
pub job_threads: Option<usize>,
pub build_cache: Option<crate::build_cache::Settings>,
pub base_path: String,
hoisted: plan::Hoist,
receipts: Option<(HashMap<String, PreparedReceipt>, TemplateContext)>,
seq: Arc<AtomicUsize>,
synced: Mutex<HashSet<PathBuf>>,
docker_ok: OnceLock<Result<(), String>>,
refused: HashMap<usize, String>,
}
struct BuildCacheRun {
key: String,
inputs: crate::build_cache::KeyInputs,
stat: crate::build_cache::JobCache,
notes: Vec<String>,
active: bool,
}
impl BuildCacheRun {
fn off(note: String) -> Self {
BuildCacheRun {
key: String::new(),
inputs: Default::default(),
stat: Default::default(),
notes: vec![note],
active: false,
}
}
}
#[derive(Default)]
struct ShardHold {
job: String,
reports: Vec<crate::shard::ShardOutcome>,
outcomes: Vec<JobOutcome>,
handled: BTreeSet<String>,
cancel: BTreeSet<String>,
errored: bool,
last: Option<usize>,
done: bool,
}
pub(crate) fn shard_script(ts: &dag::TaskShard, root: &Path) -> Result<String, String> {
use crate::shard::{adapters, Shard};
let adapter = adapters::from_info(&ts.runner, &root.to_string_lossy())
.ok_or_else(|| format!("no adapter for runner `{}`", ts.runner.runner))?;
let inv = adapter.invoke(
&Shard {
index: ts.index,
tests: ts.tests.clone(),
load: 0,
},
ts.count,
ts.mode,
);
adapters::script_of(&inv).ok_or_else(|| "a test name cannot be put in a command".to_string())
}
const PIPE_FD: i32 = 3;
const PIPE_SCRIPT: &str = "/dev/fd/3";
fn re(cell: &'static OnceLock<Regex>, pat: &str) -> &'static Regex {
cell.get_or_init(|| Regex::new(pat).unwrap())
}
fn mask_in_file(path: &Path, secret: &str) {
if secret.len() < 4 {
return;
}
if let Ok(text) = fs::read_to_string(path) {
if text.contains(secret) {
let _ = fs::write(path, text.replace(secret, "***"));
}
}
}
fn slug_of(s: &str) -> String {
let mut out: String = s
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect();
while out.contains("--") {
out = out.replace("--", "-");
}
out.trim_matches('-').chars().take(40).collect()
}
pub fn strip_ansi(s: &str) -> String {
static R: OnceLock<Regex> = OnceLock::new();
re(&R, r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07]*\x07|\r")
.replace_all(s, "")
.into_owned()
}
pub fn tail(path: &Path, n: usize) -> Vec<String> {
let mut f = match File::open(path) {
Ok(f) => f,
Err(_) => return vec![],
};
let len = f.metadata().map(|m| m.len()).unwrap_or(0);
let start = len.saturating_sub(256 * 1024);
let _ = f.seek(SeekFrom::Start(start));
let mut buf = Vec::new();
let _ = f.read_to_end(&mut buf);
let text = strip_ansi(&String::from_utf8_lossy(&buf));
let lines: Vec<String> = text
.lines()
.filter(|l| !l.trim().is_empty() && !is_controller_line(l))
.map(String::from)
.collect();
lines[lines.len().saturating_sub(n)..].to_vec()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Exit {
Code(i32),
Timeout,
Cancelled,
}
struct Semaphore {
free: Mutex<usize>,
cv: Condvar,
}
impl Semaphore {
fn acquire(&self) {
let mut f = self.free.lock().unwrap();
while *f == 0 {
f = self.cv.wait(f).unwrap();
}
*f -= 1;
}
fn release(&self) {
*self.free.lock().unwrap() += 1;
self.cv.notify_one();
}
}
pub fn compose_projects(script: &str) -> Vec<String> {
static FLAG: OnceLock<Regex> = OnceLock::new();
static ENV: OnceLock<Regex> = OnceLock::new();
let flag = re(
&FLAG,
r"(?:^|\s)(?:-p|--project-name)(?:\s+|=)[\x22']?([A-Za-z0-9][A-Za-z0-9_-]*)",
);
let env = re(
&ENV,
r"\bCOMPOSE_PROJECT_NAME=[\x22']?([A-Za-z0-9][A-Za-z0-9_-]*)",
);
let mut out: Vec<String> = env
.captures_iter(&script.replace("\\\n", " "))
.map(|c| c[1].to_string())
.collect();
for cmd in compose_commands(script) {
out.extend(
flag.captures_iter(compose_globals(&cmd))
.map(|c| c[1].to_string()),
);
}
let mut seen = HashSet::new();
out.retain(|p| seen.insert(p.clone()));
out
}
const RUN_LABEL_MAX: usize = 60;
fn run_label(workflow: &str, job: &str, step: &str) -> String {
let clip = |s: &str, max: usize| -> String {
let one_line = s.split_whitespace().collect::<Vec<_>>().join(" ");
if one_line.chars().count() <= max {
return one_line;
}
let head: String = one_line.chars().take(max.saturating_sub(1)).collect();
format!("{head}…")
};
let head = format!("{} / {} / ", clip(workflow, 100), clip(job, 100));
let room = RUN_LABEL_MAX.saturating_sub(head.chars().count());
let step = clip(step, room.max(8));
clip(&format!("{head}{step}"), RUN_LABEL_MAX)
}
const CONTROLLER_PREFIX: &str = "task-traffic-controller: ";
fn is_controller_line(line: &str) -> bool {
line.starts_with(CONTROLLER_PREFIX)
}
fn command_spoke(b: &[u8]) -> bool {
let text = String::from_utf8_lossy(b);
let mut lines = text.split('\n');
let rest = lines.next_back().unwrap_or_default();
lines.any(|l| !is_controller_line(l))
|| !rest.is_empty() && !is_controller_line(rest) && !CONTROLLER_PREFIX.starts_with(rest)
}
fn is_ledger_timeout_line(line: &str) -> bool {
line.strip_prefix(CONTROLLER_PREFIX)
.is_some_and(|r| r.starts_with("ledger: timed out"))
}
fn ledger_timed_out(log: &Path, from: u64) -> bool {
let Ok(mut f) = File::open(log) else {
return false;
};
let mut b = Vec::new();
if f.seek(SeekFrom::Start(from)).is_err() || f.read_to_end(&mut b).is_err() {
return false;
}
let text = String::from_utf8_lossy(&b);
let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
lines.iter().all(|l| is_controller_line(l)) && lines.iter().any(|l| is_ledger_timeout_line(l))
}
fn compose_commands(script: &str) -> Vec<String> {
let joined = script.replace("\\\n", " ");
let mut out = Vec::new();
for line in joined.lines() {
for marker in ["docker compose", "docker-compose"] {
for (at, _) in line.match_indices(marker) {
let rest = &line[at + marker.len()..];
out.push(
rest.split(['|', ';', '&'])
.next()
.unwrap_or(rest)
.to_string(),
);
}
}
}
out
}
fn compose_files(script: &str) -> Vec<Option<String>> {
static WORD: OnceLock<Regex> = OnceLock::new();
let mut out = Vec::new();
for cmd in compose_commands(script) {
let words: Vec<&str> = re(&WORD, r"\S+")
.find_iter(compose_globals(&cmd))
.map(|m| m.as_str())
.collect();
let mut named = false;
for (i, w) in words.iter().enumerate() {
let file = match *w {
"-f" | "--file" => words.get(i + 1).copied(),
w => w.strip_prefix("--file="),
};
if let Some(f) = file {
named = true;
let f = f.trim_matches(['"', '\'']);
out.push((!f.contains('$')).then(|| f.to_string()));
}
}
if !named {
for f in [
"compose.yaml",
"compose.yml",
"docker-compose.yaml",
"docker-compose.yml",
] {
out.push(Some(f.to_string()));
}
}
}
out
}
fn compose_fixed(text: &str) -> bool {
static R: OnceLock<Regex> = OnceLock::new();
re(
&R,
r#"(?m)^\s*container_name\s*:|^\s*-\s*["']?(\d{1,3}(\.\d{1,3}){3}:)?\d{2,5}:\d|^\s*published\s*:\s*["']?\d"#,
)
.is_match(text)
}
fn docker_run_fixed(script: &str) -> bool {
static RUN: OnceLock<Regex> = OnceLock::new();
static FIXED: OnceLock<Regex> = OnceLock::new();
let fixed = re(
&FIXED,
r#"\s--name[=\s]|\s(-p|--publish)[=\s]+["']?(\d{1,3}(\.\d{1,3}){3}:)?\d{2,5}:"#,
);
re(&RUN, r"docker\s+(container\s+)?run\b[^|;&\n]*")
.find_iter(&script.replace("\\\n", " "))
.any(|m| fixed.is_match(m.as_str()))
}
fn compose_globals(args: &str) -> &str {
const VALUED: [&str; 10] = [
"-f",
"--file",
"-p",
"--project-name",
"--env-file",
"--profile",
"--project-directory",
"--ansi",
"--parallel",
"--progress",
];
static WORD: OnceLock<Regex> = OnceLock::new();
let mut value_next = false;
for m in re(&WORD, r"\S+").find_iter(args) {
let t = m.as_str();
if t == "\\" {
continue;
}
if value_next {
value_next = false;
} else if t.starts_with('-') {
value_next = VALUED.contains(&t);
} else {
return &args[..m.start()];
}
}
args
}
const NPM_SHIM: &str = r#"#!/bin/sh
# Written by local-ci for one run.
real="__REAL__"
own() {
[ -f node_modules/.local-ci-shared ] || return 0
t=$(cat node_modules/.local-ci-shared)
rm -rf .node_modules.local-ci
cp -cR "$t" .node_modules.local-ci 2>/dev/null || cp -a --reflink=auto "$t" .node_modules.local-ci || exit 1
rm -rf node_modules && mv .node_modules.local-ci node_modules
}
sub="$1"
case "$sub" in
ci|install|i) ;;
rebuild|rb|uninstall|un|remove|r|update|up|link|ln|prune|dedupe|ddp) own; exec "$real" "$@" ;;
*) exec "$real" "$@" ;;
esac
shift
for a in "$@"; do
case "$a" in
-*) ;;
*) own; exec "$real" "$sub" "$@" ;;
esac
done
dir=$(pwd -P)
ws=$(cd "${GITHUB_WORKSPACE:-/}" 2>/dev/null && pwd -P)
sum=$(cksum package-lock.json 2>/dev/null | cut -d' ' -f1)
# relative to the workspace, so a unit's copy of the worktree keeps setup's marks
key=$(printf '%s' "${dir#"$ws"}$LOCAL_CI_INSTALL_SCOPE" | cksum | cut -d' ' -f1)
marks="$LOCAL_CI_MARKS"
mkdir -p "$marks"
until mkdir "$marks/$key.lock" 2>/dev/null; do sleep 1; done
trap 'rmdir "$marks/$key.lock" 2>/dev/null' EXIT INT TERM
if [ -f "$marks/$key-$sum" ] && [ -d node_modules ]; then
echo "local-ci: node_modules in $dir was installed earlier in this run; skipping npm $sub" >&2
exit 0
fi
own
"$real" "$sub" "$@"
rc=$?
if [ "$rc" -eq 0 ]; then : > "$marks/$key-$sum"; fi
exit "$rc"
"#;
fn writes_node_modules(script: &str) -> bool {
static R: OnceLock<Regex> = OnceLock::new();
R.get_or_init(|| {
Regex::new(r"\b(npm (ci|install|i|rebuild|uninstall|update|link|prune|dedupe)|prisma generate|patch-package|yarn|pnpm)\b").unwrap()
})
.is_match(script)
}
pub fn parse_file_command(text: &str) -> Vec<(String, String)> {
let mut out = Vec::new();
let mut lines = text.lines();
while let Some(line) = lines.next() {
if let Some((k, delim)) = line.split_once("<<") {
if !k.contains('=') {
let mut val = Vec::new();
for l in lines.by_ref() {
if l == delim {
break;
}
val.push(l);
}
out.push((k.to_string(), val.join("\n")));
continue;
}
}
if let Some((k, v)) = line.split_once('=') {
if !k.is_empty() {
out.push((k.to_string(), v.to_string()));
}
}
}
out
}
struct PortMap {
declared: Option<u16>,
container: u16,
actual: u16,
}
fn rewrite_ports(text: &str, maps: &[PortMap]) -> String {
let mut s = text.to_string();
for m in maps {
if let Some(d) = m.declared {
let r = Regex::new(&format!(r"\b(localhost|127\.0\.0\.1|0\.0\.0\.0):{d}\b")).unwrap();
s = r
.replace_all(&s, format!("${{1}}:{}", m.actual).as_str())
.into_owned();
let a = Regex::new(&format!(
r#"(-e\s+|--env[=\s]\s*)?\b([A-Za-z_][A-Za-z0-9_]*=["']?){d}\b"#
))
.unwrap();
s = a
.replace_all(&s, |c: ®ex::Captures| {
if c.get(1).is_none() && port_key(c[2].trim_end_matches(['=', '"', '\''])) {
format!("{}{}", &c[2], m.actual)
} else {
c[0].to_string()
}
})
.into_owned();
}
}
s
}
fn port_key(k: &str) -> bool {
static R: OnceLock<Regex> = OnceLock::new();
re(&R, r"(?i)^(([a-z0-9_]*_)?|pg)port(_[a-z0-9_]*)?$").is_match(k)
}
fn port_literal(v: &str) -> Option<u16> {
v.trim().parse::<u16>().ok().filter(|p| *p >= 1024)
}
fn assigned_ports(script: &str) -> Vec<u16> {
static R: OnceLock<Regex> = OnceLock::new();
re(
&R,
r#"(-e\s+|--env[=\s]\s*)?\b([A-Za-z_][A-Za-z0-9_]*)=["']?(\d{4,5})\b"#,
)
.captures_iter(script)
.filter(|c| c.get(1).is_none() && port_key(&c[2]))
.filter_map(|c| port_literal(&c[3]))
.collect()
}
fn map_literals(ports: impl IntoIterator<Item = u16>, maps: &mut Vec<PortMap>) -> Result<()> {
let mut held = Vec::new();
for p in ports {
if maps.iter().any(|m| m.declared == Some(p)) {
continue;
}
let actual = loop {
let l = std::net::TcpListener::bind(("127.0.0.1", 0)).context("no free port")?;
let a = l.local_addr()?.port();
held.push(l);
if !maps.iter().any(|m| m.actual == a) {
break a;
}
};
maps.push(PortMap {
declared: Some(p),
container: p,
actual,
});
}
Ok(())
}
fn rename_compose_projects(script: &str, tag: &str) -> String {
static FLAG: OnceLock<Regex> = OnceLock::new();
static ENV: OnceLock<Regex> = OnceLock::new();
let suffix = format!("-{tag}");
let rename = |c: ®ex::Captures| {
if c[2].ends_with(&suffix) {
c[0].to_string()
} else {
format!("{}{}{suffix}", &c[1], &c[2])
}
};
let s = re(
&ENV,
r#"(\bCOMPOSE_PROJECT_NAME=["']?)([A-Za-z0-9][A-Za-z0-9_-]*)"#,
)
.replace_all(script, rename)
.into_owned();
let flag = re(
&FLAG,
r#"((?:^|\s)(?:-p|--project-name)(?:\s+|=)["']?)([A-Za-z0-9][A-Za-z0-9_-]*)"#,
);
let mut out = String::new();
let mut rest = s.as_str();
loop {
let at = ["docker compose", "docker-compose"]
.iter()
.filter_map(|m| rest.find(m).map(|i| i + m.len()))
.min();
let Some(at) = at else {
out.push_str(rest);
break;
};
out.push_str(&rest[..at]);
let seg = &rest[at..];
let b = seg.as_bytes();
let end = (0..b.len())
.find(|&i| {
matches!(b[i], b'|' | b';' | b'&')
|| (b[i] == b'\n' && (i == 0 || b[i - 1] != b'\\'))
})
.unwrap_or(b.len());
let globals = compose_globals(&seg[..end]);
out.push_str(&flag.replace_all(globals, rename));
out.push_str(&seg[globals.len()..end]);
rest = &seg[end..];
}
out
}
fn rewritable_mention(w: &Workflow, job: &Job, h: u16) -> bool {
let hs = h.to_string();
let host = Regex::new(&format!(r"\b(localhost|127\.0\.0\.1|0\.0\.0\.0):{h}\b")).unwrap();
let assign = Regex::new(&format!(r#"\b([A-Za-z_][A-Za-z0-9_]*)=["']?{h}\b"#)).unwrap();
let in_text = |t: &str| {
t.contains("job.services.")
|| host.is_match(t)
|| assign.captures_iter(t).any(|c| port_key(&c[1]))
};
let in_env = |pairs: &[(String, String)]| {
pairs
.iter()
.any(|(k, v)| (port_key(k) && v.trim() == hs) || in_text(v))
};
in_env(&w.env)
|| in_env(&job.env)
|| job
.steps
.iter()
.any(|s| in_env(&s.env) || s.run.as_deref().is_some_and(in_text))
}
fn rewrite_env_value(key: &str, val: &str, maps: &[PortMap]) -> String {
for m in maps {
if let Some(d) = m.declared {
if port_key(key) && val.trim() == d.to_string() {
return m.actual.to_string();
}
}
}
rewrite_ports(val, maps)
}
impl<'a> Runner<'a> {
pub(crate) fn select_derived(
mut self,
selection: crate::driver::dispatch::Selection,
facts: crate::driver::PortableFacts,
) -> Self {
self.selected = Some((selection, facts));
self
}
pub fn new(
ctx: &'a ExecContext,
fp: &'a FrozenPlan,
ws: &Workspace,
opts: Opts,
) -> Result<Self> {
fp.require_git_source()?;
Self::construct(ctx, fp, ws, opts, None)
}
pub(crate) fn new_pinned(
ctx: &'a ExecContext,
input: &'a crate::source_execute::PinnedExecution<'a>,
ws: &'a crate::source_execute::PinnedWorkspace,
opts: Opts,
provider: &'a dyn crate::source_execute::PinnedWorkspaceProvider,
) -> Result<Self> {
input.validate(input.plan)?;
ws.validate(input)?;
Self::construct(
ctx,
input.plan,
ws.workspace(),
opts,
Some((input, ws, provider)),
)
}
fn validate_source(&self) -> Result<()> {
match self.pinned {
Some((input, ws, _)) => {
input.validate(self.fp)?;
ws.validate(input)
}
None => self.fp.require_git_source(),
}
}
fn source_identity(&self) -> String {
self.fp
.source
.receipt_identity()
.expect("validated execution source")
}
fn workspace_name(&self) -> String {
if let Some((_, ws, _)) = self.pinned {
return ws.namespace.clone();
}
self.fp
.source
.execution_commit
.as_deref()
.unwrap_or(&self.fp.digest)
.chars()
.take(7)
.collect()
}
fn resource_name(&self) -> String {
let n = self.seq.fetch_add(1, Ordering::SeqCst);
match self.pinned {
Some((_, ws, _)) => format!("local-ci-{}-{n}-{}", ws.namespace, std::process::id()),
None => format!("local-ci-{}-{n}", std::process::id()),
}
}
fn construct(
ctx: &'a ExecContext,
fp: &'a FrozenPlan,
ws: &Workspace,
opts: Opts,
pinned: Option<(
&'a crate::source_execute::PinnedExecution<'a>,
&'a crate::source_execute::PinnedWorkspace,
&'a dyn crate::source_execute::PinnedWorkspaceProvider,
)>,
) -> Result<Self> {
let base_path = ctx.var("PATH").unwrap_or_default().to_string();
let plan = fp.to_plan();
let refused = (0..plan.selected.len())
.filter_map(|wf| Some((wf, artifact_io::workflow_refusal(&plan, wf)?)))
.collect();
Ok(Runner {
selected: None,
pinned,
ctx,
fp,
refused,
hoisted: plan::hoist(&plan),
plan,
receipts: None,
repo_root: ws.repo_root.clone(),
wt: ws.root.clone(),
run_dir: ws.run_dir.clone(),
tools: ws.tools.clone(),
lock_file: ws.lock_file.clone(),
slug: fp.repository.clone().unwrap_or_default(),
opts,
job_threads: None,
build_cache: None,
base_path,
seq: pinned
.map(|(_, ws, _)| ws.sequence.clone())
.unwrap_or_else(|| {
static SEQUENCE: OnceLock<Arc<AtomicUsize>> = OnceLock::new();
SEQUENCE
.get_or_init(|| Arc::new(AtomicUsize::new(0)))
.clone()
}),
synced: Mutex::new(HashSet::new()),
docker_ok: OnceLock::new(),
})
}
fn github_ctx(&self, ws: &Path, w: &Workflow, event: &str, job: &str) -> Value {
let base = match &self.fp.source.pinned {
Some(p) => p.base_branch.clone().unwrap_or_default(),
None => crate::git::branch_name(
self.fp
.source
.base
.as_deref()
.expect("Git execution requires a base"),
),
};
let head = self.fp.branch.clone().unwrap_or_default();
let pr = event == "pull_request";
json!({
"event_name": event,
"event": if pr { json!({"pull_request": {"draft": false, "number": 0, "head": {"ref": head, "sha": self.fp.source.execution_commit}, "base": {"ref": base}}, "action": "synchronize"}) } else { json!({"ref": format!("refs/heads/{head}")}) },
"sha": self.fp.source.execution_commit,
"ref": if pr { "refs/pull/0/merge".to_string() } else { format!("refs/heads/{head}") },
"ref_name": if pr { "0/merge".to_string() } else { head.clone() },
"head_ref": if pr { head.clone() } else { String::new() },
"base_ref": if pr { base } else { String::new() },
"repository": self.slug,
"repository_owner": self.slug.split('/').next().unwrap_or(""),
"workflow": w.name,
"job": job,
"run_id": "0",
"run_number": "0",
"run_attempt": "1",
"actor": "local-ci",
"server_url": "https://github.com",
"api_url": "https://api.github.com",
"workspace": ws.to_string_lossy(),
})
}
fn runner_ctx(&self) -> Value {
let os = if cfg!(target_os = "macos") {
"macOS"
} else {
"Linux"
};
let arch = if cfg!(target_arch = "aarch64") {
"ARM64"
} else {
"X64"
};
json!({"os": os, "arch": arch, "temp": self.tools.join("tmp").to_string_lossy(), "tool_cache": self.tools.join("tool-cache").to_string_lossy(), "name": "local-ci"})
}
fn base_env(&self, gh: &Value, extra_path: &[String]) -> Vec<(String, String)> {
let s = |k: &str| gh.get(k).map(expr::to_string).unwrap_or_default();
let mut path: Vec<String> = vec![self.tools.join("bin").to_string_lossy().into_owned()];
path.extend(extra_path.iter().rev().cloned());
path.push(self.tools.join("venv/bin").to_string_lossy().into_owned());
path.push(
self.tools
.join("npm-global/bin")
.to_string_lossy()
.into_owned(),
);
path.push(self.base_path.clone());
let ws = s("workspace");
vec![
("CI".into(), "true".into()),
("GITHUB_ACTIONS".into(), "true".into()),
("LOCAL_CI".into(), "1".into()),
(
"LOCAL_CI_MARKS".into(),
self.marks(Path::new(&ws)).to_string_lossy().into_owned(),
),
("GITHUB_WORKSPACE".into(), ws),
("GITHUB_REF".into(), s("ref")),
("GITHUB_REF_NAME".into(), s("ref_name")),
("GITHUB_HEAD_REF".into(), s("head_ref")),
("GITHUB_BASE_REF".into(), s("base_ref")),
("GITHUB_EVENT_NAME".into(), s("event_name")),
("GITHUB_REPOSITORY".into(), self.slug.clone()),
("GITHUB_WORKFLOW".into(), s("workflow")),
("GITHUB_JOB".into(), s("job")),
("GITHUB_RUN_ID".into(), "0".into()),
("GITHUB_RUN_NUMBER".into(), "0".into()),
(
"RUNNER_OS".into(),
self.runner_ctx()["os"].as_str().unwrap_or("").into(),
),
(
"RUNNER_TEMP".into(),
self.tools.join("tmp").to_string_lossy().into_owned(),
),
(
"NPM_CONFIG_PREFIX".into(),
self.tools.join("npm-global").to_string_lossy().into_owned(),
),
("PIP_REQUIRE_VIRTUALENV".into(), "true".into()),
(
"LOCAL_CI_TOOLS".into(),
self.tools.to_string_lossy().into_owned(),
),
("GIT_CONFIG_COUNT".into(), "3".into()),
(
"GIT_CONFIG_KEY_0".into(),
"url./dev/null/local-ci-blocks-push/.pushInsteadOf".into(),
),
("GIT_CONFIG_VALUE_0".into(), "https://".into()),
(
"GIT_CONFIG_KEY_1".into(),
"url./dev/null/local-ci-blocks-push/.pushInsteadOf".into(),
),
("GIT_CONFIG_VALUE_1".into(), "git@".into()),
(
"GIT_CONFIG_KEY_2".into(),
"url./dev/null/local-ci-blocks-push/.pushInsteadOf".into(),
),
("GIT_CONFIG_VALUE_2".into(), "ssh://".into()),
("GIT_TERMINAL_PROMPT".into(), "0".into()),
("PATH".into(), path.join(":")),
]
.into_iter()
.chain(
self.fp
.source
.execution_commit
.clone()
.map(|sha| ("GITHUB_SHA".into(), sha)),
)
.collect()
}
fn hide_token(&self, text: String) -> String {
match self.ctx.github_token_if_fetched() {
Some(t) if t.len() >= 4 => text.replace(t, "***"),
_ => text,
}
}
#[allow(clippy::too_many_arguments)]
fn shell(
&self,
native_scope: &native_step::NativeScope,
cwd: &Path,
script: &str,
shell: Option<&str>,
env: &[(String, String)],
timeout: Option<Duration>,
log: &Path,
key: Option<String>,
label: &str,
piped: bool,
weight: Option<usize>,
) -> Result<(Exit, Duration)> {
let mut attempt = 0;
let mut queued = Duration::ZERO;
loop {
let from = fs::metadata(log).map(|m| m.len()).unwrap_or(0);
let (r, q) = self.shell_once(
native_scope,
cwd,
script,
shell,
env,
timeout,
log,
key.clone(),
label,
piped,
weight,
)?;
queued += q;
let failed = matches!(r, Exit::Code(c) if c != 0);
if !(failed
&& attempt < 3
&& self.opts.executor.is_none()
&& self.opts.traffic_controller.is_some()
&& ledger_timed_out(log, from))
{
return Ok((r, queued));
}
attempt += 1;
std::thread::sleep(Duration::from_secs(attempt));
}
}
#[allow(clippy::too_many_arguments)]
fn shell_once(
&self,
native_scope: &native_step::NativeScope,
cwd: &Path,
script: &str,
shell: Option<&str>,
env: &[(String, String)],
timeout: Option<Duration>,
log: &Path,
key: Option<String>,
label: &str,
piped: bool,
weight: Option<usize>,
) -> Result<(Exit, Duration)> {
let n = self.seq.fetch_add(1, Ordering::SeqCst);
let script_name = if self.pinned.is_some() {
format!("step-{}-{n}.sh", self.workspace_name())
} else {
format!("step-{n}.sh")
};
let file = self.tools.join("scripts").join(script_name);
let turn = self.tools.join(format!("scripts/step-{n}.turn"));
let queued =
self.opts.executor.is_none() && self.opts.traffic_controller.is_some() && key.is_some();
let marked = queued && matches!(shell.map(str::trim), None | Some("bash") | Some("sh"));
let sh_family = matches!(shell.map(str::trim), None | Some("bash") | Some("sh"));
let close = if piped && sh_family {
format!("exec {PIPE_FD}<&-; ")
} else {
String::new()
};
let body = if marked {
let mark = shlex::try_quote(&turn.to_string_lossy())
.map(|q| format!(": > {q} 2>/dev/null || true; "))
.unwrap_or_default();
format!("{close}{mark}{script}")
} else {
format!("{close}{script}")
};
let f = if piped {
PIPE_SCRIPT.to_string()
} else {
write_private(&file, &body)?;
file.to_string_lossy().into_owned()
};
let mut argv: Vec<String> = match shell.map(str::trim) {
None | Some("bash") => vec![
"bash".into(),
"--noprofile".into(),
"--norc".into(),
"-eo".into(),
"pipefail".into(),
f,
],
Some("sh") => vec!["sh".into(), "-e".into(), f],
Some("python") => vec!["python3".into(), f],
Some(custom) if custom.contains("{0}") && piped => bail!(
"the step's script holds the GitHub token, which is handed over a pipe that `shell: {custom}` cannot read; use bash, sh or python for a step that uses github.token"
),
Some(custom) if custom.contains("{0}") => shlex::split(&custom.replace("{0}", &f))
.ok_or_else(|| anyhow!("bad shell `{custom}`"))?,
Some(other) => bail!("unsupported shell `{other}`"),
};
if let (Some(c), Some(k), true) = (
&self.opts.traffic_controller,
key.clone(),
self.opts.executor.is_none(),
) {
let mut w = vec![c.to_string_lossy().into_owned(), "exec".into()];
if let Some(n) = weight {
w.extend(["--weight".into(), n.to_string()]);
}
w.extend(["--key".into(), k, "--".into()]);
w.append(&mut argv);
argv = w;
}
if !cwd.is_dir() {
fs::write(
log,
format!(
"local-ci: working-directory {} does not exist\n",
cwd.display()
),
)?;
return Ok((Exit::Code(1), Duration::ZERO));
}
if let Some(ex) = &self.opts.executor {
self.ctx.cancel.external_execution_started();
return self.shell_via_executor(
ex.as_ref(),
n,
&file,
argv,
cwd,
env,
timeout,
log,
key,
&body,
piped,
);
}
let out = OpenOptions::new().create(true).append(true).open(log)?;
let err = out.try_clone()?;
let mut cmd = self.ctx.command(&argv[0]);
if self.pinned.is_some() && self.fp.source.execution_commit.is_none() {
cmd.env_remove("GITHUB_SHA");
}
cmd.args(&argv[1..])
.current_dir(cwd)
.stdin(Stdio::null())
.stdout(out)
.stderr(err)
.process_group(0);
for (k, v) in env {
cmd.env(k, v);
}
if self.opts.traffic_controller.is_some() && !label.is_empty() {
cmd.env("TASK_TRAFFIC_CONTROLLER_LABEL", label);
}
let pipe = if piped {
let (r, w) = script_pipe(&self.tools.join(format!("scripts/step-{n}.fifo")))?;
let rfd = std::os::fd::AsRawFd::as_raw_fd(&r);
unsafe {
cmd.pre_exec(move || {
if rfd == PIPE_FD {
let fl = libc::fcntl(rfd, libc::F_GETFD);
if fl < 0 || libc::fcntl(rfd, libc::F_SETFD, fl & !libc::FD_CLOEXEC) < 0 {
return Err(std::io::Error::last_os_error());
}
} else if libc::dup2(rfd, PIPE_FD) < 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
Some((r, w))
} else {
None
};
let child = cmd
.spawn()
.with_context(|| format!("cannot start {}", argv[0]))?;
let wrapped = self.opts.traffic_controller.is_some() && key.is_some();
let mut child = native_step::NativeStep::new(child, self.ctx.cancel.clone(), wrapped);
let writer_stop = child.writer_stop();
if let Some((r, w)) = pipe {
drop(r);
let body = body.clone();
let stop = writer_stop.clone();
child.set_writer(std::thread::spawn(move || {
write_until_stopped(w, body.as_bytes(), &stop)
}));
}
let spawned = (Instant::now(), std::time::SystemTime::now());
let mut started: Option<Instant> = if self.opts.traffic_controller.is_some() {
None
} else {
Some(Instant::now())
};
let mut seen = 0u64;
let mut term_at: Option<Instant> = None;
let mut timed_out = false;
let status = loop {
if let Some(st) = child.observe()? {
break st;
}
if started.is_none() && marked && turn.exists() {
started = Some(Instant::now());
}
if started.is_none() {
if let Ok(mut lf) = File::open(log) {
let len = lf.metadata().map(|m| m.len()).unwrap_or(0);
if len > seen {
let _ = lf.seek(SeekFrom::Start(seen));
let mut b = Vec::new();
let _ = lf.read_to_end(&mut b);
if command_spoke(&b) {
started = Some(Instant::now());
}
seen += b
.iter()
.rposition(|&c| c == b'\n')
.map_or(0, |i| i as u64 + 1);
}
}
}
let over = matches!((timeout, started), (Some(t), Some(s)) if s.elapsed() > t);
if (over || self.ctx.cancel.is_cancelled()) && term_at.is_none() {
timed_out = over;
child.signal(libc::SIGTERM);
term_at = Some(Instant::now());
}
if term_at.is_some_and(|t| t.elapsed() > Duration::from_secs(10)) {
child.signal(libc::SIGKILL);
}
std::thread::sleep(Duration::from_millis(200));
};
child.finish(native_scope);
if !piped {
let _ = fs::remove_file(&file);
}
let waited = if marked {
let got_turn = fs::metadata(&turn).and_then(|m| m.modified()).ok();
let _ = fs::remove_file(&turn);
match got_turn {
Some(t) => t.duration_since(spawned.1).unwrap_or(Duration::ZERO),
None => spawned.0.elapsed(),
}
} else if queued {
started.map_or_else(
|| spawned.0.elapsed(),
|s| s.saturating_duration_since(spawned.0),
)
} else {
Duration::ZERO
};
if timed_out {
return Ok((Exit::Timeout, waited));
}
if self.ctx.cancel.is_cancelled() {
return Ok((Exit::Cancelled, waited));
}
Ok((
Exit::Code(status.code().unwrap_or(
128 + std::os::unix::process::ExitStatusExt::signal(&status).unwrap_or(0),
)),
waited,
))
}
#[allow(clippy::too_many_arguments)]
fn shell_via_executor(
&self,
ex: &dyn StepExecutor,
n: usize,
file: &Path,
argv: Vec<String>,
cwd: &Path,
env: &[(String, String)],
timeout: Option<Duration>,
log: &Path,
key: Option<String>,
body: &str,
piped: bool,
) -> Result<(Exit, Duration)> {
let mut vars = self.ctx.env().clone();
if self.pinned.is_some() && self.fp.source.execution_commit.is_none() {
vars.remove("GITHUB_SHA");
}
vars.extend(env.iter().cloned());
let (writer_stop, mut writer, mut script_fd, mut read_end) =
(Arc::new(AtomicBool::new(false)), None, None, None);
if piped {
let (r, w) = script_pipe(&self.tools.join(format!("scripts/step-{n}.fifo")))?;
script_fd = Some(ScriptPipe {
read_fd: std::os::fd::AsRawFd::as_raw_fd(&r),
child_fd: PIPE_FD,
});
read_end = Some(r);
let (body, stop) = (body.to_string(), writer_stop.clone());
writer = Some(std::thread::spawn(move || {
write_until_stopped(w, body.as_bytes(), &stop)
}));
}
let req = StepRequest {
key,
argv,
cwd: cwd.to_path_buf(),
env: vars.into_iter().collect(),
log: log.to_path_buf(),
timeout,
script_pipe: script_fd,
cancel: self.ctx.cancel.clone(),
};
let res = ex.run(&req);
writer_stop.store(true, Ordering::SeqCst);
if let Some(h) = writer {
let _ = h.join();
}
drop(read_end);
if !piped {
let _ = fs::remove_file(file);
}
let done = res?;
let waited = Duration::try_from_secs_f64(done.queue_wait_secs.unwrap_or(0.0).max(0.0))
.unwrap_or(Duration::ZERO);
let exit = match done.exit {
Exit::Code(_) if self.ctx.cancel.is_cancelled() => Exit::Cancelled,
e => e,
};
Ok((exit, waited))
}
fn log_path(&self, wf: &str, job: &str, n: usize, label: &str) -> PathBuf {
let dir = self.run_dir.join(format!(
"{}-{}",
slug_of(
crate::report::short(&self.fp.config.default_workflows_dir, wf)
.trim_end_matches(".yml")
.trim_end_matches(".yaml")
),
slug_of(job)
));
let _ = fs::create_dir_all(&dir);
dir.join(format!("{:02}-{}.log", n, slug_of(label)))
}
pub fn prepare_tools(&self) -> Result<()> {
self.validate_source()?;
for d in [
"scripts",
"tmp",
"npm-global/bin",
"files",
"bin",
"installed",
] {
fs::create_dir_all(self.tools.join(d))?;
}
if let Some(npm) = self
.base_path
.split(':')
.map(|d| Path::new(d).join("npm"))
.find(|p| p.is_file())
{
let shim = self.tools.join("bin/npm");
fs::write(&shim, NPM_SHIM.replace("__REAL__", &npm.to_string_lossy()))?;
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&shim, fs::Permissions::from_mode(0o755))?;
}
let wants_pip = self.plan.selected.iter().any(|s| {
s.wf.jobs.iter().any(|j| {
j.steps.iter().any(|st| {
st.run
.as_deref()
.is_some_and(|r| r.contains("pip install") || r.contains("pip3 install"))
})
})
});
if wants_pip {
let ok = self
.ctx
.command("python3")
.arg("-m")
.arg("venv")
.arg(self.tools.join("venv"))
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false);
if !ok {
eprintln!(
"local-ci: could not create a Python venv; `pip install` steps will be refused"
);
}
}
Ok(())
}
pub fn set_receipts(
&mut self,
receipts: HashMap<String, PreparedReceipt>,
tctx: TemplateContext,
) {
self.receipts = Some((receipts, tctx));
}
pub fn task_recipes(&self) -> Result<Vec<(String, SetupRecipe)>> {
self.fp
.tasks
.iter()
.map(|t| {
Ok((
t.id.clone(),
setup::derive_in(&self.plan, &self.hoisted, t)?,
))
})
.collect()
}
pub fn run_recipe(&self, recipe: &SetupRecipe, key: &str) -> Result<PreparedSetup> {
let native_scope = native_step::NativeScope::default();
self.validate_source()?;
if recipe.steps.is_empty() {
return Ok(PreparedSetup {
receipt: PreparedReceipt::empty(key, &self.source_identity()),
steps: vec![],
});
}
let workspace = match setup::ensure_workspace_id(&self.wt) {
Ok(id) => id,
Err(e) => {
return Ok(PreparedSetup {
receipt: PreparedReceipt::empty(key, &self.source_identity()),
steps: vec![StepResult {
label: "setup".into(),
outcome: Outcome::Error(format!("cannot record the workspace id: {e:#}")),
exit: None,
secs: 0.0,
log: None,
note: None,
}],
});
}
};
let covered = setup::covered_by(recipe);
let dirs: BTreeSet<String> = recipe.steps.iter().map(|s| s.dir.clone()).collect();
let before = setup::top_level_entries(&self.wt, &dirs);
let mut out = Vec::new();
let mut prepared: Vec<PreparedStep> = Vec::new();
let mut notes: Vec<setup::ReceiptNote> = Vec::new();
for (i, s) in recipe.steps.iter().enumerate() {
if let Some(by) = covered.get(&s.id) {
if prepared.iter().any(|p| &p.id == by) {
prepared.push(PreparedStep {
id: s.id.clone(),
how: PreparedHow::SameAs { step: by.clone() },
});
continue;
}
}
let label = format!(
"{}$ {}",
if s.dir.is_empty() { "." } else { &s.dir },
s.label
);
let found = self
.plan
.selected
.iter()
.position(|x| x.wf.file == s.workflow)
.filter(|wi| {
self.plan.selected[*wi]
.wf
.jobs
.iter()
.any(|j| j.id == s.job)
});
let Some(wi) = found else {
out.push(StepResult {
label,
outcome: Outcome::Error(format!(
"the plan has no job {} in {}",
s.job, s.workflow
)),
exit: None,
secs: 0.0,
log: None,
note: None,
});
break;
};
let sel = &self.plan.selected[wi];
let gh = self.github_ctx(&self.wt, &sel.wf, &sel.event, &s.job);
let mut env = self.base_env(&gh, &[]);
env.extend(s.env.iter().cloned());
env.extend(s.ignored_env.iter().cloned());
let log = self.log_path("setup", "", i + 1, &format!("{}-{}", s.dir, s.label));
let t0 = Instant::now();
let cwd = self.wt.join(&s.dir);
let res = self
.shell(
&native_scope,
&cwd,
&s.run,
s.shell.as_deref(),
&env,
Some(Duration::from_secs(1800)),
&log,
Some(format!("local-ci setup {label}")),
&run_label(&sel.wf.name, &s.job, &s.label),
false,
None,
)
.map(|(exit, _)| exit);
let (outcome, exit) = match res {
Ok(Exit::Code(0)) => (Outcome::Pass, Some(0)),
Ok(Exit::Code(c)) => (Outcome::Fail, Some(c)),
Ok(Exit::Timeout) => (Outcome::Error("timed out".into()), None),
Ok(Exit::Cancelled) => (Outcome::Error("cancelled".into()), None),
Err(e) => (Outcome::Error(format!("{e:#}")), None),
};
let stop = outcome != Outcome::Pass;
let note = setup::ignored_env_note(s);
if !stop {
prepared.push(PreparedStep {
id: s.id.clone(),
how: PreparedHow::Ran,
});
if let Some(text) = ¬e {
notes.push(setup::ReceiptNote {
step: s.id.clone(),
text: text.clone(),
});
}
}
out.push(StepResult {
label,
outcome,
exit,
secs: t0.elapsed().as_secs_f64(),
log: Some(log),
note,
});
if stop {
break;
}
}
drop(native_scope);
let artifacts = if out.iter().all(|r| r.outcome == Outcome::Pass) {
setup::artifact_digests(
&self.wt,
&before,
&setup::top_level_entries(&self.wt, &dirs),
)
} else {
vec![]
};
Ok(PreparedSetup {
receipt: PreparedReceipt {
schema_version: crate::wire::wire_version(),
template_key: key.into(),
source: self.source_identity(),
workspace,
steps: prepared,
artifacts,
notes,
},
steps: out,
})
}
pub fn run_units(&self) -> Result<Vec<UnitResult>> {
self.validate_source()?;
self.fp.require_git_source()?;
let sem = Semaphore {
free: Mutex::new(self.opts.parallel.max(1)),
cv: Condvar::new(),
};
let results: Mutex<Vec<(usize, UnitResult)>> = Mutex::new(Vec::new());
let isolate = self.plan.units.len() > 1;
std::thread::scope(|scope| {
for (i, u) in self.plan.units.iter().enumerate() {
let sem = &sem;
let results = &results;
scope.spawn(move || {
if let Some(why) = self.refused.get(&u.wf) {
results
.lock()
.unwrap()
.push((i, self.refused_unit(i, u, why)));
return;
}
let t0 = Instant::now();
let requested_at_ms = now_ms();
let lock = if self.unit_locked(u) {
self.lock().ok()
} else {
None
};
let locked_at = t0.elapsed().as_secs_f64();
sem.acquire();
let waited = UnitWait {
lock: locked_at,
parallel: t0.elapsed().as_secs_f64() - locked_at,
requested_at_ms,
};
let r = if isolate && !self.ctx.cancel.is_cancelled() {
self.run_unit_in_copy(i, u, waited)
} else {
self.run_unit(i, u, waited, &self.wt)
};
sem.release();
drop(lock);
results.lock().unwrap().push((i, r));
});
}
});
let mut r = results.into_inner().unwrap();
r.sort_by_key(|(i, _)| *i);
Ok(r.into_iter().map(|(_, u)| u).collect())
}
fn refused_entries(
&self,
wf: usize,
id: &str,
why: &str,
only: Option<usize>,
) -> Vec<JobResult> {
let w = &self.plan.selected[wf].wf;
let base = self.plan.job(wf, id).name.clone().unwrap_or(id.to_string());
let displays: Vec<String> = match dag::matrix_plan(self.fp.job(wf, id)) {
dag::MatrixPlan::Static(v) => v
.iter()
.enumerate()
.filter(|(i, _)| only.is_none_or(|o| o == *i))
.map(|(_, c)| format!("{base} ({})", matrix::describe(c)))
.collect(),
_ => vec![base],
};
displays
.into_iter()
.map(|display| JobResult {
workflow: w.file.clone(),
job: id.to_string(),
display,
outcome: Outcome::Error(why.to_string()),
secs: 0.0,
steps: vec![],
cancelled: false,
time: None,
build_cache: None,
os_note: None,
})
.collect()
}
fn refused_unit(&self, ui: usize, u: &Unit, why: &str) -> UnitResult {
let w = &self.plan.selected[u.wf].wf;
UnitResult {
unit: Some(ui),
workflow: w.file.clone(),
jobs: u
.jobs
.iter()
.flat_map(|id| self.refused_entries(u.wf, id, why, None))
.collect(),
waited_secs: 0.0,
copy_secs: None,
cached: None,
outcomes: vec![],
}
}
pub(crate) fn refused_task(&self, task: &ExecutionTask) -> Option<TaskResult> {
let wf = self
.plan
.selected
.iter()
.position(|s| s.wf.file == task.workflow)?;
let why = self.refused.get(&wf)?;
let only = task.variant.as_ref().map(|v| v.index);
Some(TaskResult {
schema_version: crate::wire::wire_version(),
task: task.id.clone(),
jobs: task
.jobs
.iter()
.flat_map(|id| self.refused_entries(wf, id, why, only))
.collect(),
outcomes: task
.jobs
.iter()
.map(|id| JobOutcome {
job: id.clone(),
variant: only,
status: JobStatus::Failure,
outputs: Default::default(),
skipped: Some(why.clone()),
ancestor_failed: false,
})
.collect(),
receipt_ignored: None,
artifacts: vec![],
shard: None,
})
}
pub(crate) fn lock(&self) -> Result<File> {
use fs2::FileExt;
let f = OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&self.lock_file)?;
f.lock_exclusive()?;
Ok(f)
}
fn isolated(&self) -> bool {
self.opts.portool.is_some() && self.wt.join(".portool.toml").is_file()
}
fn unit_locked(&self, u: &Unit) -> bool {
u.exclusive
&& (!self.isolated()
|| u.jobs
.iter()
.any(|id| !self.plan.job(u.wf, id).services.is_empty()))
}
fn container_slot(&self) -> Result<Option<File>> {
use fs2::FileExt;
let dir = self.lock_file.parent().context("no lock directory")?;
fs::create_dir_all(dir)?;
loop {
for i in 0..self.opts.containers.max(1) {
let f = OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(dir.join(format!("containers-{i}.lock")))?;
if f.try_lock_exclusive().is_ok() {
return Ok(Some(f));
}
}
if self.ctx.cancel.is_cancelled() {
return Ok(None);
}
std::thread::sleep(Duration::from_millis(500));
}
}
fn fixed_resources(&self, ws: &Path, w: &Workflow, job: &Job, cm: &Map<String, Value>) -> bool {
let ctx = Ctx::new(cm, Status::Success);
job.steps.iter().any(|s| {
let Some(run) = &s.run else { return false };
let script = expr::interpolate(run, &ctx).unwrap_or_else(|_| run.clone());
let dir = ws.join(plan::step_dir(w, job, s));
docker_run_fixed(&script)
|| compose_files(&script).iter().any(|f| match f {
Some(f) => fs::read_to_string(dir.join(f)).is_ok_and(|t| compose_fixed(&t)),
None => true,
})
})
}
fn marks(&self, ws: &Path) -> PathBuf {
self.tools
.join("installed")
.join(ws.file_name().unwrap_or_default())
}
fn copy_of(&self, from: &Path, to: &Path) -> Result<()> {
self.validate_source()?;
if let Some((_, _, provider)) = self.pinned {
provider.fork(from, to)?;
} else {
crate::git::clone_worktree(
self.ctx,
&self.repo_root,
from,
to,
&self.source_identity(),
self.fp.config.link_node_modules,
)?;
}
let marks = self.marks(to);
fs::create_dir_all(&marks)?;
for e in fs::read_dir(self.marks(from))
.into_iter()
.flatten()
.flatten()
{
if e.file_type().is_ok_and(|t| t.is_file()) {
fs::copy(e.path(), marks.join(e.file_name()))?;
}
}
Ok(())
}
fn remove_copy(&self, ws: &Path) {
if !self.opts.keep {
let _ = self.release_ports(ws);
if let Some((_, _, provider)) = self.pinned {
let _ = provider.remove(ws);
} else {
crate::git::remove_worktree(self.ctx, &self.repo_root, ws, &self.opts.trash);
}
}
}
fn run_unit_in_copy(&self, ui: usize, u: &Unit, waited: UnitWait) -> UnitResult {
let n = if self.pinned.is_some() {
self.seq.fetch_add(1, Ordering::SeqCst)
} else {
ui + 1
};
let ws = self.wt.with_file_name(format!(
"{}-u{n}-{}",
self.workspace_name(),
std::process::id()
));
let t0 = Instant::now();
let r = match self.copy_of(&self.wt, &ws) {
Ok(()) => {
let copy_secs = t0.elapsed().as_secs_f64();
UnitResult {
copy_secs: Some(copy_secs),
..self.run_unit(ui, u, waited, &ws)
}
}
Err(e) => {
let w = &self.plan.selected[u.wf].wf;
let reason = format!("cannot copy the worktree: {e:#}");
let mut jobs: Vec<JobResult> = u
.jobs
.iter()
.map(|id| JobResult {
workflow: w.file.clone(),
job: id.clone(),
display: self.plan.job(u.wf, id).name.clone().unwrap_or(id.clone()),
outcome: Outcome::Error(reason.clone()),
secs: 0.0,
steps: vec![],
cancelled: false,
time: None,
build_cache: None,
os_note: None,
})
.collect();
charge(&mut jobs, waited);
UnitResult {
unit: Some(ui),
workflow: w.file.clone(),
jobs,
waited_secs: waited.total(),
copy_secs: None,
cached: None,
outcomes: vec![],
}
}
};
self.remove_copy(&ws);
r
}
pub fn release_ports(&self, ws: &Path) -> Result<()> {
self.release_ports_checked(ws)
}
pub(crate) fn release_ports_checked(&self, ws: &Path) -> Result<()> {
if self.opts.portool.is_some() {
self.ctx.cancel.port_release_pending(ws);
}
self.validate_source()?;
let Some(bin) = &self.opts.portool else {
return Ok(());
};
if (ws == self.wt || self.synced.lock().unwrap().contains(ws))
&& ws.join(".portool.toml").is_file()
{
crate::portool::release_checked(self.ctx, bin, ws)?;
self.synced.lock().unwrap().remove(ws);
}
self.ctx.cancel.port_release_confirmed(ws);
Ok(())
}
fn run_unit(&self, ui: usize, u: &Unit, waited: UnitWait, ws: &Path) -> UnitResult {
let w = &self.plan.selected[u.wf].wf;
let locked = self.unit_locked(u);
let mut inputs = TaskInputs::default();
let mut jobs = Vec::new();
let mut outcomes: Vec<JobOutcome> = Vec::new();
let mut shards: HashMap<String, ShardHold> = HashMap::new();
let copy_id = (ws != self.wt)
.then(|| setup::ensure_workspace_id(ws).ok())
.flatten();
let origin = setup::workspace_id(&self.wt);
let mut copy_checked: HashMap<String, bool> = HashMap::new();
if copy_id.is_some() {
if let Some((m, _)) = &self.receipts {
for t in self.fp.tasks.iter().filter(|t| t.unit == ui) {
if let Some(r) = m.get(&t.id) {
copy_checked
.entry(t.id.clone())
.or_insert_with(|| setup::verify_artifacts(r, ws, true).is_ok());
}
}
}
}
for task in self.fp.tasks.iter().filter(|t| t.unit == ui) {
if task.variant.as_ref().is_some_and(|v| v.index > 0) {
continue;
}
let receipt = self.receipts.as_ref().and_then(|(m, c)| {
m.get(&task.id).map(|r| match ©_id {
Some(id) if origin.as_deref() == Some(r.workspace.as_str()) => {
(r.rebound(id), c)
}
_ => (r.clone(), c),
})
});
let verify = copy_id.is_some() && !copy_checked.get(&task.id).copied().unwrap_or(false);
if let Some(ts) = &task.shard {
let hold = shards.entry(ts.group.clone()).or_default();
if hold.cancel.contains(&task.id) {
let why = "cancelled: another shard of the job failed (fail-fast)";
for id in &task.jobs {
let job = self.plan.job(u.wf, id);
let r = JobResult {
workflow: w.file.clone(),
job: id.clone(),
display: format!(
"{} (shard {}/{})",
job.name.clone().unwrap_or_else(|| id.clone()),
ts.index + 1,
ts.count
),
outcome: Outcome::Skip(why.into()),
secs: 0.0,
steps: vec![],
cancelled: true,
time: None,
build_cache: None,
os_note: None,
};
hold.outcomes.push(outcome_of(id, None, &r, &Map::new()));
jobs.push(r);
}
hold.last = jobs.len().checked_sub(1);
hold.handled.insert(task.id.clone());
self.settle_shards(task, hold, &mut jobs, &mut outcomes, &mut inputs);
continue;
}
}
match self.run_task(
ws,
task,
&inputs,
receipt.as_ref().map(|(r, c)| (r, *c)),
verify,
locked,
true,
) {
Ok(r) => {
if let Some(ts) = &task.shard {
for o in &r.outcomes {
inputs.run_cancelled |= o.status == JobStatus::Cancelled;
}
jobs.extend(r.jobs);
let hold = shards.entry(ts.group.clone()).or_default();
hold.last = jobs.len().checked_sub(1);
hold.outcomes.extend(r.outcomes);
hold.reports.extend(r.shard);
hold.handled.insert(task.id.clone());
self.settle_shards(task, hold, &mut jobs, &mut outcomes, &mut inputs);
continue;
}
for o in r.outcomes {
inputs.run_cancelled |= o.status == JobStatus::Cancelled;
outcomes.push(o.clone());
inputs.needs.insert(o.job.clone(), o);
}
jobs.extend(r.jobs);
}
Err(e) => {
let reason = format!("{e:#}");
for id in &task.jobs {
let o = JobOutcome {
job: id.clone(),
variant: None,
status: JobStatus::Failure,
outputs: Default::default(),
skipped: Some(reason.clone()),
ancestor_failed: false,
};
if let Some(ts) = &task.shard {
shards.entry(ts.group.clone()).or_default().outcomes.push(o);
} else {
outcomes.push(o.clone());
inputs.needs.insert(id.clone(), o);
}
}
for id in &task.jobs {
let job = self.plan.job(u.wf, id);
let base = job.name.clone().unwrap_or(id.clone());
let displays: Vec<String> =
match crate::dag::matrix_plan(self.fp.job(u.wf, id)) {
crate::dag::MatrixPlan::Static(v) => v
.iter()
.map(|c| format!("{base} ({})", matrix::describe(c)))
.collect(),
_ => vec![base],
};
for display in displays {
jobs.push(JobResult {
workflow: w.file.clone(),
job: id.clone(),
display,
outcome: Outcome::Error(reason.clone()),
secs: 0.0,
steps: vec![],
cancelled: false,
time: None,
build_cache: None,
os_note: None,
});
}
}
if let Some(ts) = &task.shard {
let hold = shards.entry(ts.group.clone()).or_default();
hold.last = jobs.len().checked_sub(1);
hold.errored = true;
hold.handled.insert(task.id.clone());
self.settle_shards(task, hold, &mut jobs, &mut outcomes, &mut inputs);
}
}
}
}
for (group, hold) in shards.iter_mut().filter(|(_, h)| !h.done) {
self.finish_shards(group, hold, &mut jobs, &mut outcomes, &mut inputs);
}
charge(&mut jobs, waited);
UnitResult {
unit: Some(ui),
workflow: w.file.clone(),
jobs,
waited_secs: waited.total(),
copy_secs: None,
cached: None,
outcomes,
}
}
fn settle_shards(
&self,
task: &ExecutionTask,
hold: &mut ShardHold,
jobs: &mut [JobResult],
outcomes: &mut Vec<JobOutcome>,
inputs: &mut TaskInputs,
) {
let Some(ts) = &task.shard else { return };
hold.job = task.jobs.join("+");
let group = self.fp.shard_groups.iter().find(|g| g.id == ts.group);
if let Some(g) = group {
let agg = crate::complete::aggregate_shard_group(g, &hold.reports);
hold.cancel.extend(agg.cancel);
if g.fail_fast && hold.errored {
hold.cancel.extend(
g.shards
.iter()
.filter(|s| !hold.handled.contains(*s))
.cloned(),
);
}
if hold.handled.len() < g.shards.len() {
return;
}
}
self.finish_shards(&ts.group, hold, jobs, outcomes, inputs);
}
fn finish_shards(
&self,
group: &str,
hold: &mut ShardHold,
jobs: &mut [JobResult],
outcomes: &mut Vec<JobOutcome>,
inputs: &mut TaskInputs,
) {
if std::mem::replace(&mut hold.done, true) {
return;
}
let mut problems = match self.fp.shard_groups.iter().find(|g| g.id == group) {
Some(g) => crate::complete::aggregate_shard_group(g, &hold.reports).problems(),
None => vec![format!("the plan has no shard group `{group}`")],
};
problems.extend(task::conflicting_outputs(&hold.outcomes));
let mut o = combine(&hold.job, std::mem::take(&mut hold.outcomes));
if !problems.is_empty() && o.status == JobStatus::Success {
let why = problems.join("; ");
o.status = JobStatus::Failure;
o.skipped = Some(why.clone());
if let Some(last) = hold.last.and_then(|i| jobs.get_mut(i)) {
last.outcome = Outcome::Error(why);
}
}
outcomes.push(o.clone());
inputs.needs.insert(o.job.clone(), o);
}
pub(crate) fn task_locked(&self, t: &ExecutionTask) -> bool {
t.exclusive && (!self.isolated() || !t.services.is_empty())
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn run_task(
&self,
ws: &Path,
task: &ExecutionTask,
inputs: &TaskInputs,
prepared: Option<(&PreparedReceipt, &TemplateContext)>,
verify_contents: bool,
locked: bool,
whole_matrix: bool,
) -> Result<TaskResult> {
self.validate_source()?;
anyhow::ensure!(
self.selected
.as_ref()
.is_none_or(|(selection, _)| &selection.task == task),
"selected dispatch task mismatch"
);
let wi = self
.plan
.selected
.iter()
.position(|s| s.wf.file == task.workflow)
.with_context(|| format!("the plan has no workflow {}", task.workflow))?;
let sel = &self.plan.selected[wi];
let w = &sel.wf;
if let Some(ts) = &task.shard {
if let Err(why) = self.check_shard_task(wi, task, ts) {
bail!("task {} is a shard of a split job, but {why}", task.id);
}
}
for id in &task.jobs {
let job = self.plan.job(wi, id);
if let Some(n) = job
.needs
.iter()
.find(|n| !task.jobs.contains(n) && !inputs.needs.contains_key(*n))
{
bail!(
"task {} needs the result of job `{n}`; none was given",
task.id
);
}
}
let only = match (&task.variant, whole_matrix) {
(Some(v), false) => Some(v.index),
_ => None,
};
let mut receipt_ignored = None;
let places = match prepared {
Some((r, tctx)) => match setup::derive_in(&self.plan, &self.hoisted, task)?
.prepared_places(
r,
&self.source_identity(),
setup::workspace_id(ws).as_deref(),
ws,
tctx,
verify_contents,
) {
Ok(p) => p,
Err(why) => {
receipt_ignored = Some(why);
HashMap::new()
}
},
None => HashMap::new(),
};
let none = HashSet::new();
let mut needs_ctx = inputs.context();
let mut jobs = Vec::new();
let mut outcomes = Vec::new();
let mut shard = None;
for id in &task.jobs {
let job = self.plan.job(wi, id);
let ancestor_failed = job.needs.iter().any(|n| {
outcomes
.iter()
.find(|o: &&JobOutcome| &o.job == n)
.or_else(|| inputs.needs.get(n))
.is_some_and(JobOutcome::failed_or_ancestor_failed)
});
let results = self.run_job(
ws,
w,
&sel.event,
job,
&needs_ctx,
ancestor_failed,
inputs.run_cancelled || self.ctx.cancel.is_cancelled(),
places.get(id).unwrap_or(&none),
locked,
only,
task.shard.as_ref(),
);
let parts: Vec<JobOutcome> = results
.iter()
.enumerate()
.map(|(i, (r, o))| outcome_of(id, only.or(Some(i)), r, o))
.collect();
let outcome = match only {
Some(_) => parts.into_iter().next().unwrap_or_else(|| JobOutcome {
job: id.clone(),
variant: only,
status: JobStatus::Success,
outputs: Default::default(),
skipped: None,
ancestor_failed: false,
}),
None => combine(id, parts),
};
let outcome = JobOutcome {
ancestor_failed,
..outcome
};
needs_ctx.insert(id.clone(), task::ctx_of(&outcome));
let results: Vec<JobResult> = results.into_iter().map(|r| r.0).collect();
if let Some(ts) = &task.shard {
shard = Some(self.shard_outcome(ws, w, job, task, ts, results.first()));
}
jobs.extend(results);
outcomes.push(outcome);
}
Ok(TaskResult {
schema_version: crate::wire::wire_version(),
task: task.id.clone(),
shard,
jobs,
outcomes,
receipt_ignored,
artifacts: artifact_io::published_by(
&self.run_dir,
&task.workflow,
&task
.jobs
.iter()
.map(|j| dag::node_id(&task.workflow, j))
.collect::<Vec<_>>(),
),
})
}
fn check_shard_task(
&self,
wi: usize,
task: &ExecutionTask,
ts: &dag::TaskShard,
) -> Result<(), String> {
use crate::shard::{adapters, SplitMode};
let w = &self.plan.selected[wi].wf;
let bad = |what: &str| {
Err(format!(
"step {} of its job is not a command of runner `{}` that can be given the shard's tests ({what})",
ts.step, ts.runner.runner
))
};
let job = (task.jobs.len() == 1).then(|| self.plan.job(wi, &task.jobs[0]));
let Some((job, step)) = job.and_then(|j| Some((j, j.steps.get(ts.step)?))) else {
return bad("there is no such step");
};
let Some(run) = step.run.as_ref().filter(|_| step.uses.is_none()) else {
return bad("it is not a `run` step");
};
if step.continue_on_error {
return bad("it may fail without failing the job");
}
if !matches!(
plan::resolved_shell(w, job, step).as_deref().map(str::trim),
None | Some("bash") | Some("sh")
) {
return bad("its shell does not read one command");
}
if plan::step_dir(w, job, step) != ts.dir {
return bad("its working directory is not where the tests were listed");
}
let Some(parsed) = adapters::parse_command(run) else {
return bad("it is not one plain command");
};
if parsed.runner != ts.runner.runner
|| parsed.args != ts.runner.config
|| !parsed.blocked.is_empty()
{
return bad("it is not the command the shards were made from");
}
if crate::shard::isolation::reason_in(&w.env, job).is_some() {
return bad("the job starts a container, a server or a service its shards would share");
}
if crate::shard::isolation::coverage_reason(&w.env, job).is_some() {
return bad("the job collects coverage, which its shards would each measure in part");
}
let caps = adapters::from_info(&ts.runner, "").map(|a| a.capabilities());
let Some(caps) = caps else {
return bad("the shard has no tests to run");
};
if ts.mode == SplitMode::Single || (ts.mode == SplitMode::Listed && ts.tests.is_empty()) {
return bad("the shard has no tests to run");
}
if (ts.mode == SplitMode::Listed && !caps.targets)
|| (ts.mode == SplitMode::Native && !caps.native_shard)
{
return bad("the runner cannot divide its tests that way");
}
Ok(())
}
fn shard_outcome(
&self,
ws: &Path,
w: &Workflow,
job: &Job,
task: &ExecutionTask,
ts: &dag::TaskShard,
result: Option<&JobResult>,
) -> crate::shard::ShardOutcome {
use crate::shard::{adapters, CommandOutput, ShardOutcome};
let none = |exit_ok| ShardOutcome {
job_id: job.id.clone(),
shard_id: task.id.clone(),
tests: vec![],
exit_ok,
parsed: false,
};
let Some(step) = job.steps.get(ts.step) else {
return none(false);
};
let root = ws.join(plan::step_dir(w, job, step));
let ran = result.and_then(|r| r.steps.get(ts.step));
let (Some(ran), Some(adapter)) = (
ran,
adapters::from_info(&ts.runner, &root.to_string_lossy()),
) else {
return none(false);
};
let log = ran
.log
.as_ref()
.and_then(|l| fs::read(l).ok())
.map(|b| String::from_utf8_lossy(&b).into_owned());
let out = CommandOutput {
stdout: log.clone().unwrap_or_default(),
stderr: String::new(),
success: ran.outcome == Outcome::Pass && ran.exit == Some(0),
exit: ran.exit,
};
let mut o = adapter.collect_given(&job.id, &task.id, &out, &ts.tests);
o.parsed &= log.is_some();
o
}
#[allow(clippy::too_many_arguments)]
fn run_job(
&self,
ws: &Path,
w: &Workflow,
event: &str,
job: &Job,
needs: &Map<String, Value>,
ancestor_failed: bool,
run_cancelled: bool,
prepared: &HashSet<usize>,
locked: bool,
only: Option<usize>,
shard: Option<&dag::TaskShard>,
) -> Vec<(JobResult, Map<String, Value>)> {
let gh = self.github_ctx(ws, w, event, &job.id);
let skip = |display: String, reason: String| {
(
JobResult {
workflow: w.file.clone(),
job: job.id.clone(),
display,
outcome: Outcome::Skip(reason),
secs: 0.0,
steps: vec![],
cancelled: false,
time: None,
build_cache: None,
os_note: None,
},
Map::new(),
)
};
let cancelled_skip = |display: String| {
let mut r = skip(display, "cancelled".into());
r.0.cancelled = true;
r
};
let error = |display: String, reason: String| {
(
JobResult {
workflow: w.file.clone(),
job: job.id.clone(),
display,
outcome: Outcome::Error(reason),
secs: 0.0,
steps: vec![],
cancelled: false,
time: None,
build_cache: None,
os_note: None,
},
Map::new(),
)
};
let host = os_legs::Family::host();
let legs = if self.selected.is_none() {
self.os_legs_of(job, &gh, needs, shard)
} else {
None
};
let evaluated = match &self.selected {
Some((selection, facts)) => {
selection.worker_evaluation(gh, self.runner_ctx(), needs, facts)
}
None => crate::job_evaluate::evaluate_job(
job,
gh,
self.runner_ctx(),
needs,
ancestor_failed,
run_cancelled,
only,
shard,
),
};
let mut out = Vec::new();
let mut notes: Vec<(usize, String)> = Vec::new();
let mut todo = Vec::new();
for (k, entry) in evaluated.entries.into_iter().enumerate() {
match entry.decision {
crate::job_evaluate::Decision::Run(cm) => {
let leg = legs.as_ref().and_then(|l| l.get(only.unwrap_or(k)));
match leg {
Some(OsLeg {
os: Some((family, label)),
twin: Some(twin),
}) => out.push(Some(skip(
entry.display,
os_legs::not_run_reason(label, *family, host, twin),
))),
_ => {
if let Some((family, label)) =
leg.and_then(|l| l.os.as_ref()).filter(|(f, _)| *f != host)
{
notes.push((out.len(), os_legs::ran_on_note(label, *family, host)));
}
todo.push((out.len(), cm, entry.display));
out.push(None);
}
}
}
crate::job_evaluate::Decision::Skip(reason) => {
out.push(Some(skip(entry.display, reason)))
}
crate::job_evaluate::Decision::Error(reason) => {
out.push(Some(error(entry.display, reason)))
}
}
}
let exclusive = plan::is_exclusive(job);
let failed = AtomicBool::new(false);
let stop = job.fail_fast.then_some(&failed);
let one = |ws: &Path, cm: Map<String, Value>, display: String| {
let requested_at_ms = now_ms();
let t_lock = Instant::now();
let lock = if exclusive && !locked && self.fixed_resources(ws, w, job, &cm) {
self.lock().ok()
} else {
None
};
let wait_lock = t_lock.elapsed().as_secs_f64();
let t_slot = Instant::now();
let slot = if exclusive {
match self.container_slot() {
Ok(Some(s)) => Some(s),
Ok(None) => return cancelled_skip(display),
Err(_) => None,
}
} else {
None
};
let wait_slot = t_slot.elapsed().as_secs_f64();
if self.ctx.cancel.is_cancelled() {
return cancelled_skip(display);
}
if stop.is_some_and(|s| s.load(Ordering::SeqCst)) {
return skip(display, "fail-fast".into());
}
let mut r = self.run_combo(ws, w, job, prepared, cm, display, stop, shard);
drop(slot);
drop(lock);
let secs = r.0.secs;
let t = r.0.time.get_or_insert_with(|| JobTime {
work_secs: secs,
..JobTime::default()
});
t.wait_lock_secs += wait_lock;
t.wait_slot_secs += wait_slot;
if t.started_at_ms > 0 {
t.requested_at_ms = requested_at_ms.min(t.started_at_ms);
}
if matches!(r.0.outcome, Outcome::Fail | Outcome::Error(_)) {
failed.store(true, Ordering::SeqCst);
}
r
};
let at_once = job.max_parallel.unwrap_or(usize::MAX);
if todo.len() > 1
&& at_once > 1
&& (self.opts.traffic_controller.is_some() || self.opts.executor.is_some())
&& (!exclusive || !locked)
{
let done = Mutex::new(Vec::new());
let sem = Semaphore {
free: Mutex::new(at_once),
cv: Condvar::new(),
};
std::thread::scope(|scope| {
for (i, cm, display) in todo {
let (one, done, sem) = (&one, &done, &sem);
scope.spawn(move || {
sem.acquire();
let copy = self.wt.with_file_name(format!(
"{}-c{}-{}",
self.workspace_name(),
self.seq.fetch_add(1, Ordering::SeqCst),
std::process::id()
));
let r = match self.copy_of(ws, ©) {
Ok(()) => one(©, cm, display),
Err(e) => error(display, format!("cannot copy the worktree: {e:#}")),
};
self.remove_copy(©);
sem.release();
done.lock().unwrap().push((i, r));
});
}
});
for (i, r) in done.into_inner().unwrap() {
out[i] = Some(r);
}
} else {
for (i, cm, display) in todo {
out[i] = Some(one(ws, cm, display));
}
}
for (i, note) in notes {
if let Some(Some((r, _))) = out.get_mut(i) {
r.os_note = Some(note);
}
}
out.into_iter().flatten().collect()
}
fn os_legs_of(
&self,
job: &Job,
gh: &Value,
needs: &Map<String, Value>,
shard: Option<&dag::TaskShard>,
) -> Option<Vec<OsLeg>> {
job.runs_on.as_ref()?;
let mut all = job.clone();
all.cond = Some("always()".into());
let entries = crate::job_evaluate::evaluate_job(
&all,
gh.clone(),
self.runner_ctx(),
needs,
false,
false,
None,
shard,
)
.entries;
let mut contexts = Vec::new();
let mut displays = Vec::new();
for entry in entries {
match entry.decision {
crate::job_evaluate::Decision::Run(cm) => {
contexts.push(cm);
displays.push(entry.display);
}
_ => return None,
}
}
let os_of: Vec<Option<(os_legs::Family, String)>> = contexts
.iter()
.map(|cm| os_legs::family_of_leg(job, cm))
.collect();
let twin_of: Vec<Option<usize>> = if self.opts.all_os_legs {
vec![None; contexts.len()]
} else {
let legs: Vec<os_legs::Leg> = os_of
.iter()
.zip(&contexts)
.map(|(o, cm)| os_legs::Leg {
family: o.as_ref().map(|(f, _)| *f),
matrix: cm
.get("matrix")
.and_then(Value::as_object)
.cloned()
.unwrap_or_default(),
})
.collect();
os_legs::twins(os_legs::Family::host(), job, &legs)
};
Some(
os_of
.into_iter()
.zip(twin_of)
.map(|(os, twin)| OsLeg {
os,
twin: twin.map(|t| displays[t].clone()),
})
.collect(),
)
}
fn eval_env(
host: &ExecContext,
pairs: &[(String, String)],
cm: &Map<String, Value>,
into: &mut Map<String, Value>,
maps: &[PortMap],
) -> Result<bool> {
let mut secrets = false;
for (k, v) in pairs {
let mut ctx_map = cm.clone();
ctx_map.insert("env".into(), Value::Object(into.clone()));
let ctx = Ctx::new(&ctx_map, Status::Success).with_token(host);
let val = expr::interpolate(v, &ctx)?;
secrets |= ctx.used_secrets.get();
into.insert(k.clone(), Value::String(rewrite_env_value(k, &val, maps)));
}
Ok(secrets)
}
#[allow(clippy::too_many_arguments)]
fn run_combo(
&self,
ws: &Path,
w: &Workflow,
job: &Job,
prepared: &HashSet<usize>,
mut cm: Map<String, Value>,
display: String,
stop: Option<&AtomicBool>,
shard: Option<&dag::TaskShard>,
) -> (JobResult, Map<String, Value>) {
let native_scope = native_step::NativeScope::default();
let t0 = Instant::now();
let started_at_ms = now_ms();
let mut stopped = false;
let mut steps: Vec<StepResult> = Vec::new();
let mut names = Vec::new();
let finish = |outcome: Outcome, steps: Vec<StepResult>, t0: Instant| JobResult {
workflow: w.file.clone(),
job: job.id.clone(),
display: display.clone(),
outcome,
secs: t0.elapsed().as_secs_f64(),
steps,
cancelled: false,
time: None,
build_cache: None,
os_note: None,
};
let mut maps = Vec::new();
let mut services_ctx = Map::new();
if !job.services.is_empty() {
match self.start_services(w, job, &cm, &mut names) {
Ok((m, sc)) => {
maps = m;
services_ctx = sc;
}
Err(e) => {
self.stop_services(&names, &mut steps);
let mut r = finish(Outcome::Error(format!("services: {e:#}")), steps, t0);
r.cancelled = self.ctx.cancel.is_cancelled();
return (r, Map::new());
}
}
}
cm.insert(
"job".into(),
json!({"status": "success", "services": services_ctx}),
);
let exclusive = plan::is_exclusive(job);
let port_env = match &self.opts.portool {
Some(bin)
if exclusive && job.services.is_empty() && ws.join(".portool.toml").is_file() =>
{
self.synced.lock().unwrap().insert(ws.to_path_buf());
match crate::portool::sync(self.ctx, bin, ws) {
Ok(v) => v,
Err(e) => {
self.stop_services(&names, &mut steps);
return (
finish(Outcome::Error(format!("{e:#}")), steps, t0),
Map::new(),
);
}
}
}
_ => vec![],
};
let mut env_ctx = Map::new();
if let Err(e) = Self::eval_env(self.ctx, &w.env, &cm, &mut env_ctx, &maps)
.and_then(|_| Self::eval_env(self.ctx, &job.env, &cm, &mut env_ctx, &maps))
.and_then(|_| {
if exclusive {
let fixed: Vec<u16> = env_ctx
.iter()
.filter(|(k, _)| port_key(k))
.filter_map(|(_, v)| port_literal(&expr::to_string(v)))
.collect();
map_literals(fixed, &mut maps)?;
for (k, v) in env_ctx.iter_mut() {
let s = expr::to_string(v);
let r = rewrite_env_value(k, &s, &maps);
if r != s {
*v = Value::String(r);
}
}
}
Ok(())
})
{
self.stop_services(&names, &mut steps);
return (
finish(Outcome::Error(format!("env: {e:#}")), steps, t0),
Map::new(),
);
}
let mut bc = self.build_cache_start(ws, w, job, &cm, &env_ctx);
let job_min = job.timeout_minutes.unwrap_or(self.opts.job_timeout_min);
let job_timeout = Duration::from_secs_f64(60.0 * job_min);
let mut steps_ctx = Map::new();
let mut extra_env: Vec<(String, String)> = Vec::new();
let mut extra_path: Vec<String> = Vec::new();
let mut failed = false;
let compose_default = self.resource_name();
let tag = format!("lc{}", &compose_default["local-ci-".len()..]);
let mut projects = vec![compose_default.clone()];
self.ctx.cancel.track_compose(compose_default.clone());
let mut errored: Option<String> = None;
let mut cancelled = false;
let mut queue = Duration::ZERO;
for (n, s) in job.steps.iter().enumerate() {
let raw_label = s.label();
let label = if raw_label.contains("${{") {
let mut lcm = cm.clone();
lcm.insert("steps".into(), Value::Object(steps_ctx.clone()));
lcm.insert("env".into(), Value::Object(env_ctx.clone()));
expr::interpolate(&raw_label, &Ctx::new(&lcm, Status::Success)).unwrap_or(raw_label)
} else {
raw_label
};
let label = self.hide_token(label);
let st0 = Instant::now();
let push = |steps: &mut Vec<StepResult>,
outcome: Outcome,
exit: Option<i32>,
log: Option<PathBuf>,
note: Option<String>| {
steps.push(StepResult {
label: label.clone(),
outcome,
exit,
secs: st0.elapsed().as_secs_f64(),
log,
note,
});
};
stopped |= stop.is_some_and(|s| s.load(Ordering::SeqCst));
let status = if self.ctx.cancel.is_cancelled() || stopped {
Status::Cancelled
} else if failed || errored.is_some() {
Status::Failure
} else {
Status::Success
};
let mut scm = cm.clone();
scm.insert("steps".into(), Value::Object(steps_ctx.clone()));
let mut step_env = env_ctx.clone();
for (k, v) in &extra_env {
step_env.insert(k.clone(), Value::String(v.clone()));
}
scm.insert("env".into(), Value::Object(step_env.clone()));
let go = expr::condition(
s.cond.as_deref(),
&Ctx::new(&scm, status).with_token(self.ctx),
);
match go {
Ok(true) => {}
Ok(false) => {
push(
&mut steps,
Outcome::Skip(if status == Status::Success {
"if: false".into()
} else {
"earlier step failed".into()
}),
None,
None,
None,
);
record(&mut steps_ctx, &s.id, "skipped", "skipped", Map::new());
continue;
}
Err(e) => {
let e = self.hide_token(format!("{e:#}"));
push(
&mut steps,
Outcome::Error(format!("if: {e}")),
None,
None,
None,
);
errored.get_or_insert(format!("{label}: if: {e}"));
continue;
}
}
if let Some(uses) = &s.uses {
let (outcome, note) = match artifact::parse_uses(uses) {
Some(Ok(kind)) => self.artifact_step(ws, w, job, &display, n, s, &scm, kind),
Some(Err(e)) => (Outcome::Error(e), None),
None => self.check_action(uses, s, &scm),
};
let outcome = match outcome {
Outcome::Error(e) => Outcome::Error(self.hide_token(e)),
Outcome::Skip(e) => Outcome::Skip(self.hide_token(e)),
o => o,
};
let note = note.map(|n| self.hide_token(n));
if let Outcome::Error(e) = &outcome {
errored.get_or_insert(format!("{label}: {e}"));
}
let o = if matches!(outcome, Outcome::Pass) {
"success"
} else {
"skipped"
};
push(&mut steps, outcome, None, None, note);
record(&mut steps_ctx, &s.id, o, o, Map::new());
continue;
}
let Some(run) = &s.run else {
push(
&mut steps,
Outcome::Skip("no run or uses".into()),
None,
None,
None,
);
continue;
};
if prepared.contains(&n) {
push(&mut steps, Outcome::Skip("setup".into()), None, None, None);
record(&mut steps_ctx, &s.id, "success", "success", Map::new());
continue;
}
if crate::script::remote_effect(run) {
push(
&mut steps,
Outcome::Skip("pushes, publishes or deploys".into()),
None,
None,
None,
);
record(&mut steps_ctx, &s.id, "skipped", "skipped", Map::new());
continue;
}
if crate::script::global_install(run, &|c| self.ctx.find_tool(c).is_some())
== crate::script::Install::Needed
{
push(
&mut steps,
Outcome::Skip("installs system packages".into()),
None,
None,
None,
);
record(&mut steps_ctx, &s.id, "skipped", "skipped", Map::new());
continue;
}
let ctx = Ctx::new(&scm, status).with_token(self.ctx);
let script = expr::interpolate(run, &ctx);
let mut env_now = step_env.clone();
if plan::step_key(w, job, s, &self.plan.ignore_env)
.is_some_and(|k| self.hoisted.conflicting.contains(&k))
{
env_now.insert(
"LOCAL_CI_INSTALL_SCOPE".into(),
Value::String(job.id.clone()),
);
}
let env_res = Self::eval_env(self.ctx, &s.env, &scm, &mut env_now, &maps);
let secrets = ctx.used_secrets.get() || matches!(env_res, Ok(true));
let (script, mut env_now) = match (script, env_res) {
(Ok(sc), Ok(_)) => (sc, env_now),
(Err(e), _) | (_, Err(e)) => {
let e = self.hide_token(format!("{e:#}"));
push(&mut steps, Outcome::Error(e.clone()), None, None, None);
errored.get_or_insert(format!("{label}: {e}"));
continue;
}
};
let script = if exclusive {
let fixed: Vec<u16> = assigned_ports(&script)
.into_iter()
.chain(
env_now
.iter()
.filter(|(k, _)| port_key(k))
.filter_map(|(_, v)| port_literal(&expr::to_string(v))),
)
.collect();
if let Err(e) = map_literals(fixed, &mut maps) {
push(
&mut steps,
Outcome::Error(format!("{e:#}")),
None,
None,
None,
);
errored.get_or_insert(format!("{label}: {e:#}"));
continue;
}
for (k, v) in env_now.iter_mut() {
let s = expr::to_string(v);
let mut r = rewrite_env_value(k, &s, &maps);
if k == "COMPOSE_PROJECT_NAME"
&& !r.is_empty()
&& !r.ends_with(&format!("-{tag}"))
{
r = format!("{r}-{tag}");
}
if r != s {
*v = Value::String(r);
}
}
rename_compose_projects(&rewrite_ports(&script, &maps), &tag)
} else {
rewrite_ports(&script, &maps)
};
let token = self.ctx.github_token_if_fetched().filter(|t| !t.is_empty());
let step_shell = s
.shell
.as_deref()
.or(job.shell.as_deref())
.or(w.shell.as_deref());
let custom_shell = !matches!(
step_shell.map(str::trim),
None | Some("bash") | Some("sh") | Some("python")
);
let piped = token.is_some_and(|t| {
script.contains(t)
|| (!custom_shell && env_now.values().any(|v| expr::to_string(v).contains(t)))
});
if secrets {
push(
&mut steps,
Outcome::Skip("uses secrets".into()),
None,
None,
None,
);
record(&mut steps_ctx, &s.id, "skipped", "skipped", Map::new());
continue;
}
let wd = plan::step_dir(w, job, s);
let script = match shard.filter(|t| t.step == n) {
Some(ts) => match shard_script(ts, &ws.join(&wd)).and_then(|script| {
if self
.opts
.executor
.as_ref()
.is_some_and(|host| host.verify_shard_runner())
{
crate::shard::adapters::guard_version(&ts.runner, script)
} else {
Ok(script)
}
}) {
Ok(sc) => sc,
Err(e) => {
push(&mut steps, Outcome::Error(e.clone()), None, None, None);
errored.get_or_insert(format!("{label}: {e}"));
continue;
}
},
None => script,
};
let files_name = if self.pinned.is_some() {
self.resource_name()
} else {
self.seq.fetch_add(1, Ordering::SeqCst).to_string()
};
let files_dir = self.tools.join("files").join(files_name);
let _ = fs::create_dir_all(&files_dir);
{
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
let _ = fs::set_permissions(&files_dir, fs::Permissions::from_mode(0o700));
for f in ["output", "env", "path", "summary"] {
let _ = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(files_dir.join(f));
}
}
let fc = |name: &str| files_dir.join(name);
let gh = scm["github"].clone();
let mut env: Vec<(String, String)> = self.base_env(&gh, &extra_path);
env.extend(port_env.iter().cloned());
env.push((
"GITHUB_OUTPUT".into(),
fc("output").to_string_lossy().into_owned(),
));
env.push((
"GITHUB_ENV".into(),
fc("env").to_string_lossy().into_owned(),
));
env.push((
"GITHUB_PATH".into(),
fc("path").to_string_lossy().into_owned(),
));
env.push((
"GITHUB_STEP_SUMMARY".into(),
fc("summary").to_string_lossy().into_owned(),
));
env.push(("COMPOSE_PROJECT_NAME".into(), compose_default.clone()));
let from_env = env_now
.get("COMPOSE_PROJECT_NAME")
.map(expr::to_string)
.filter(|p| !p.is_empty());
for p in compose_projects(&script) {
if !projects.contains(&p) {
if exclusive && p.ends_with(&format!("-{tag}")) {
self.ctx.cancel.track_compose(p.clone());
} else {
self.ctx.cancel.track_unverified_compose(p.clone());
}
projects.push(p);
}
}
if let Some(project) = from_env {
self.ctx.cancel.track_unverified_compose(project.clone());
if !projects.contains(&project) {
projects.push(project);
}
}
if let Some(threads) = self.job_threads {
for k in crate::cpu::JOB_THREAD_ENV {
if self.ctx.var(k).is_none_or(|v| v.is_empty()) && !env_now.contains_key(k) {
env.push((k.into(), threads.to_string()));
}
}
}
for (k, v) in &env_now {
env.push((k.clone(), expr::to_string(v)));
}
let log = self.log_path(&w.file, &display, n + 1, &label);
let remaining = job_timeout.saturating_sub(t0.elapsed().saturating_sub(queue));
if remaining.is_zero() {
let _ = fs::remove_dir_all(&files_dir);
push(
&mut steps,
Outcome::Error(format!("not started: the job timed out ({job_min} min)")),
None,
None,
None,
);
record(&mut steps_ctx, &s.id, "failure", "failure", Map::new());
errored.get_or_insert(format!("{label}: the job timed out"));
continue;
}
let own = s.timeout_minutes.map(|m| Duration::from_secs_f64(m * 60.0));
let by_job = own.is_none_or(|t| remaining < t);
let timeout = own.map_or(remaining, |t| t.min(remaining));
let key = crate::demand::history_key(
&self.fp.config.default_workflows_dir,
&w.file,
&job.id,
&label,
);
let pkg = fs::read_to_string(ws.join(&wd).join("package.json")).ok();
if writes_node_modules(&plan::with_scripts(&script, pkg.as_deref())) {
if let Err(e) = crate::git::own_node_modules(self.ctx, ws) {
let e = format!("cannot copy node_modules: {e:#}");
push(&mut steps, Outcome::Error(e.clone()), None, None, None);
errored.get_or_insert(format!("{label}: {e}"));
continue;
}
}
let res = self
.shell(
&native_scope,
&ws.join(&wd),
&script,
step_shell,
&env,
Some(timeout),
&log,
Some(key),
&run_label(
&w.name,
&display,
&if s.name.is_some() {
label.clone()
} else {
format!("step {}", n + 1)
},
),
piped,
self.job_threads,
)
.map(|(exit, queued)| {
queue += queued;
exit
});
if let Some(t) = self.ctx.github_token_if_fetched() {
mask_in_file(&log, t);
}
let read = |f: &str| fs::read_to_string(fc(f)).unwrap_or_default();
let mut outputs = Map::new();
for (k, v) in parse_file_command(&read("output")) {
outputs.insert(k, Value::String(v));
}
extra_env.extend(parse_file_command(&read("env")));
extra_path.extend(
read("path")
.lines()
.filter(|l| !l.trim().is_empty())
.map(String::from),
);
let _ = fs::remove_dir_all(&files_dir);
match res {
Ok(Exit::Code(0)) => {
push(&mut steps, Outcome::Pass, Some(0), Some(log), None);
record(&mut steps_ctx, &s.id, "success", "success", outputs);
}
Ok(Exit::Code(c)) => {
let ce = s.continue_on_error;
push(
&mut steps,
Outcome::Fail,
Some(c),
Some(log),
if ce {
Some("continue-on-error".into())
} else {
None
},
);
record(
&mut steps_ctx,
&s.id,
"failure",
if ce { "success" } else { "failure" },
outputs,
);
if !ce {
failed = true;
}
}
Ok(Exit::Timeout) => {
push(
&mut steps,
Outcome::Error(if by_job {
let left = if timeout < Duration::from_secs(10) {
format!("{:.1}", timeout.as_secs_f64())
} else {
timeout.as_secs().to_string()
};
format!(
"timed out after {left}s (what was left of the job's {job_min} min)"
)
} else {
format!("timed out after {}s", timeout.as_secs())
}),
None,
Some(log),
None,
);
record(&mut steps_ctx, &s.id, "failure", "failure", outputs);
errored.get_or_insert(format!("{label}: timed out"));
}
Ok(Exit::Cancelled) => {
push(
&mut steps,
Outcome::Error("cancelled".into()),
None,
Some(log),
None,
);
if errored.is_none() {
errored = Some("cancelled".into());
cancelled = true;
}
}
Err(e) => {
push(
&mut steps,
Outcome::Error(format!("{e:#}")),
None,
Some(log),
None,
);
errored.get_or_insert(format!("{label}: {e:#}"));
}
}
}
drop(native_scope);
self.stop_services(&names, &mut steps);
let cleanup = self.ctx.cancel.cleanup_projects(self.ctx, &projects);
self.record_cleanup_warnings(&mut steps, cleanup);
let mut outputs = Map::new();
let mut ocm = cm.clone();
ocm.insert("steps".into(), Value::Object(steps_ctx));
let octx = Ctx::new(&ocm, Status::Success);
let mut dropped = Vec::new();
for (k, v) in &job.outputs {
if let Ok(val) = expr::interpolate(v, &octx) {
if self
.ctx
.github_token_if_fetched()
.is_some_and(|t| !t.is_empty() && val.contains(t))
{
dropped.push(k.clone());
outputs.insert(k.clone(), Value::String(String::new()));
continue;
}
outputs.insert(k.clone(), Value::String(val));
}
}
if !dropped.is_empty() {
let note = format!(
"job output {} holds the GitHub token: not passed on",
dropped.join(", ")
);
if let Some(last) = steps.last_mut() {
last.note = Some(match last.note.take() {
Some(n) => format!("{n}; {note}"),
None => note,
});
}
}
let outcome = if failed {
Outcome::Fail
} else if let Some(e) = errored {
Outcome::Error(e)
} else if stopped {
Outcome::Skip("fail-fast: another entry failed".into())
} else {
Outcome::Pass
};
let mut build_cache = None;
if let Some(b) = bc.as_mut() {
if b.active && matches!(outcome, Outcome::Pass) {
self.build_cache_save(b, ws);
}
if let Some(last) = steps.last_mut() {
for n in &b.notes {
last.note = Some(match last.note.take() {
Some(o) => format!("{o}; {n}"),
None => n.clone(),
});
}
}
build_cache = b.active.then(|| b.stat.clone());
}
let mut result = finish(outcome, steps, t0);
result.build_cache = build_cache;
result.cancelled = cancelled && matches!(result.outcome, Outcome::Error(_));
result.time = Some(JobTime {
work_secs: (result.secs - queue.as_secs_f64()).max(0.0),
wait_queue_secs: queue.as_secs_f64(),
requested_at_ms: started_at_ms,
started_at_ms,
finished_at_ms: now_ms().max(started_at_ms),
..JobTime::default()
});
(result, outputs)
}
fn build_cache_start(
&self,
ws: &Path,
w: &Workflow,
job: &Job,
cm: &Map<String, Value>,
env_ctx: &Map<String, Value>,
) -> Option<BuildCacheRun> {
use crate::build_cache as bc;
let s = self.build_cache.as_ref()?;
if !bc::applies(ws) {
return None;
}
let mut vars: Vec<(String, String)> = self
.ctx
.env()
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
vars.extend(env_ctx.iter().map(|(k, v)| (k.clone(), expr::to_string(v))));
for st in &job.steps {
let own: Vec<(String, String)> = st
.env
.iter()
.filter(|(k, _)| bc::affects_build(k))
.cloned()
.collect();
if own.is_empty() {
continue;
}
let mut into = env_ctx.clone();
if let Err(e) = Self::eval_env(self.ctx, &own, cm, &mut into, &[]) {
return Some(BuildCacheRun::off(format!(
"build cache: skipped (env of a step: {e:#})"
)));
}
vars.extend(
own.iter()
.filter_map(|(k, _)| Some((k.clone(), expr::to_string(into.get(k)?)))),
);
}
let env = bc::build_env(vars.iter().map(|(k, v)| (k.as_str(), v.as_str())), ws);
if bc::moves_target(&env) {
return None;
}
let (rustc, cargo) = match bc::toolchain(self.ctx, ws, &self.base_path, s.probe_timeout) {
Ok(t) => t,
Err(why) => {
return Some(BuildCacheRun::off(format!(
"build cache: skipped (toolchain: {why})"
)))
}
};
let inputs = bc::KeyInputs {
rustc,
cargo,
os_arch: bc::os_arch(),
locks: bc::lock_digests(ws),
job: format!("{}#{}", w.file, job.id),
env,
files: bc::config_digests(ws),
matrix: cm.get("matrix").map(|m| m.to_string()).unwrap_or_default(),
};
let key = bc::key(&inputs);
let mut run = BuildCacheRun {
inputs,
stat: bc::JobCache {
key: key[..12].to_string(),
..Default::default()
},
key,
notes: Vec::new(),
active: true,
};
let t = Instant::now();
match bc::restore(self.ctx, s, &run.key, ws) {
bc::Restore::Restored => {
run.stat.restored = true;
run.notes.push(format!(
"build cache: restored {} in {:.1}s",
run.stat.key,
t.elapsed().as_secs_f64()
));
}
bc::Restore::Miss => {}
bc::Restore::Skipped(why) => {
run.notes.push(format!("build cache: not restored ({why})"))
}
}
Some(run)
}
fn build_cache_save(&self, run: &mut BuildCacheRun, ws: &Path) {
use crate::build_cache as bc;
let Some(s) = self.build_cache.as_ref() else {
return;
};
let t = Instant::now();
let seq = self.seq.fetch_add(1, Ordering::SeqCst);
match bc::save_with(self.ctx, s, &run.key, ws, seq, Some(&run.inputs)) {
bc::Save::Saved => {
run.stat.saved = true;
run.notes.push(format!(
"build cache: saved {} in {:.1}s",
run.stat.key,
t.elapsed().as_secs_f64()
));
let pruned = bc::prune(self.ctx, s, Some(&run.key));
if pruned.evicted_keep {
run.stat.saved = false;
}
for w in pruned.warnings {
run.notes.push(format!("build cache: {w}"));
}
}
bc::Save::Exists => {}
bc::Save::Skipped(why) => run.notes.push(format!("build cache: not saved ({why})")),
}
}
fn check_action(
&self,
uses: &str,
s: &Step,
cm: &Map<String, Value>,
) -> (Outcome, Option<String>) {
let name = uses.split('@').next().unwrap_or(uses).to_ascii_lowercase();
let ctx = Ctx::new(cm, Status::Success).with_token(self.ctx);
let with = |k: &str| {
s.with
.iter()
.find(|(n, _)| n == k)
.and_then(|(_, v)| expr::interpolate(v, &ctx).ok())
.filter(|v| !v.is_empty())
};
let tool = |bin: &str, args: &[&str]| -> Option<String> {
let out = self.ctx.command(bin).args(args).output().ok()?;
let text = String::from_utf8_lossy(&out.stdout).to_string()
+ &String::from_utf8_lossy(&out.stderr);
out.status
.success()
.then(|| text.lines().next().unwrap_or("").trim().to_string())
};
let check = |bin: &str, args: &[&str], want: Option<String>| -> (Outcome, Option<String>) {
match tool(bin, args) {
None => (Outcome::Error(format!("`{bin}` not found")), None),
Some(have) => {
let have_v = have.trim_start_matches(|c: char| !c.is_ascii_digit());
let note = match want {
Some(w)
if !have_v
.starts_with(w.trim_start_matches('v').trim_end_matches(".x")) =>
{
Some(format!("wants {w}, have {have}"))
}
_ => Some(have),
};
(Outcome::Pass, note)
}
}
};
let version_file = |key: &str| {
with(key)
.and_then(|f| fs::read_to_string(self.wt.join(f)).ok())
.map(|t| t.trim().to_string())
};
match name.as_str() {
"actions/checkout" => (Outcome::Skip("checkout".into()), None),
"actions/setup-node" => check(
"node",
&["--version"],
with("node-version").or_else(|| version_file("node-version-file")),
),
"actions/setup-python" => check(
"python3",
&["--version"],
with("python-version").or_else(|| version_file("python-version-file")),
),
"actions/setup-go" => check("go", &["version"], None),
"actions/setup-java" => check("java", &["-version"], None),
"ruby/setup-ruby" => check("ruby", &["--version"], with("ruby-version")),
"subosito/flutter-action" => check("flutter", &["--version"], with("flutter-version")),
"dart-lang/setup-dart" => check("dart", &["--version"], None),
n if n.starts_with("dtolnay/rust-toolchain") => check(
"cargo",
&["--version"],
with("toolchain").filter(|t| t.starts_with(|c: char| c.is_ascii_digit())),
),
n if n.starts_with("actions/cache") || n.ends_with("/rust-cache") => {
(Outcome::Skip("cache".into()), None)
}
n if n.contains("upload-artifact") || n.contains("download-artifact") => {
(Outcome::Skip("artifact".into()), None)
}
_ => (Outcome::Skip(format!("action {uses}")), None),
}
}
#[allow(clippy::too_many_arguments)]
fn artifact_step(
&self,
ws: &Path,
w: &Workflow,
job: &Job,
display: &str,
step_index: usize,
s: &Step,
cm: &Map<String, Value>,
kind: artifact::Kind,
) -> (Outcome, Option<String>) {
let ctx = Ctx::new(cm, Status::Success).with_token(self.ctx);
let mut with = Vec::new();
for (k, v) in &s.with {
match expr::interpolate(v, &ctx) {
Ok(x) => with.push((k.clone(), x)),
Err(e) => return (Outcome::Error(format!("with.{k}: {e:#}")), None),
}
}
let area = artifact_io::Area::of_run(&self.run_dir, &self.fp.digest, &w.file);
let node = dag::node_id(&w.file, &job.id);
let mut holding = self
.fp
.tasks
.iter()
.filter(|t| t.workflow == w.file && t.jobs.contains(&job.id));
let task = match (holding.next(), holding.next()) {
(Some(t), None) => Some(t.id.clone()),
_ => None,
};
let who = artifact_io::Who {
job: node,
display: display.to_string(),
task,
};
let request = crate::ArtifactRequest {
kind,
area: &area,
who: &who,
workflow: &w.file,
workspace: ws,
with: &with,
step_index,
variant: job
.matrix
.as_ref()
.and_then(|_| cm.get("strategy"))
.and_then(|s| s.get("job-index"))
.and_then(Value::as_u64),
cancel: &self.ctx.cancel,
};
let done = match self.opts.executor.as_deref() {
Some(host) => {
artifact::validate_run(kind, &with).and_then(|()| host.artifact(&request))
}
None => request.run_local(),
};
match done {
Ok(note) => {
let note = match s.uses.as_deref().and_then(artifact::pin_warning) {
Some(w) => format!("{w}; {note}"),
None => note,
};
(Outcome::Pass, Some(note))
}
Err(e) => (Outcome::Error(e), None),
}
}
fn docker_ok(&self) -> Result<(), String> {
self.docker_ok
.get_or_init(|| {
self.docker(
&["info", "--format", "{{.ServerVersion}}"],
Duration::from_secs(30),
)
.map(|_| ())
.map_err(|error| format!("{error:#}"))
})
.clone()
}
fn docker(&self, args: &[&str], timeout: Duration) -> Result<String> {
let output = crate::cleanup::docker_control(self.ctx, args, timeout)?;
Ok(String::from_utf8_lossy(&output).trim().to_string())
}
fn start_services(
&self,
w: &Workflow,
job: &Job,
cm: &Map<String, Value>,
names: &mut Vec<String>,
) -> Result<(Vec<PortMap>, Map<String, Value>)> {
self.docker_ok()
.map_err(|e| anyhow!("docker is not available ({e})"))?;
let ctx = Ctx::new(cm, Status::Success);
let mut maps = Vec::new();
let mut sctx = Map::new();
for svc in &job.services {
let image = expr::interpolate(&svc.image, &ctx)?;
if self
.docker(&["image", "inspect", &image], Duration::from_secs(30))
.is_err()
{
self.docker(&["pull", "--quiet", &image], Duration::from_secs(600))
.with_context(|| format!("pull {image}"))?;
}
let name = self.resource_name();
let mut args: Vec<String> = vec![
"run".into(),
"-d".into(),
"--name".into(),
name.clone(),
"--label".into(),
"local-ci=1".into(),
];
for (k, v) in &svc.env {
args.push("-e".into());
args.push(format!("{k}={}", expr::interpolate(v, &ctx)?));
}
for (d, c) in &svc.ports {
args.push("-p".into());
args.push(match d {
Some(h) if !rewritable_mention(w, job, *h) => format!("127.0.0.1:{h}:{c}"),
_ => format!("127.0.0.1::{c}"),
});
}
let opts = expr::interpolate(&svc.options, &ctx)?;
args.extend(
shlex::split(&opts).ok_or_else(|| anyhow!("cannot parse options `{opts}`"))?,
);
args.push(image.clone());
let refs: Vec<&str> = args.iter().map(String::as_str).collect();
self.ctx.cancel.creation_started(name.clone());
let id = self.docker(&refs, Duration::from_secs(120))?;
ensure_container_id(&id)?;
self.ctx.cancel.creation_acknowledged(&name, id.clone());
names.push(id.clone());
let mut ports = Map::new();
for (d, c) in &svc.ports {
let line =
self.docker(&["port", &id, &format!("{c}/tcp")], Duration::from_secs(30))?;
let actual: u16 = line
.lines()
.next()
.and_then(|l| l.rsplit(':').next())
.and_then(|p| p.trim().parse().ok())
.ok_or_else(|| anyhow!("no host port for {c}"))?;
ports.insert(c.to_string(), Value::String(actual.to_string()));
maps.push(PortMap {
declared: *d,
container: *c,
actual,
});
}
self.wait_healthy(&id, svc, &maps)?;
sctx.insert(
svc.id.clone(),
json!({"id": id, "ports": ports, "network": ""}),
);
}
Ok((maps, sctx))
}
fn wait_healthy(&self, name: &str, svc: &Service, maps: &[PortMap]) -> Result<()> {
let has_health = svc.options.contains("--health-cmd");
let t0 = Instant::now();
let limit = Duration::from_secs(180);
loop {
if self.ctx.cancel.is_cancelled() {
bail!("cancelled");
}
let state = self.docker(&["inspect", "-f", "{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}", name], Duration::from_secs(30))?;
let mut parts = state.split_whitespace();
let (run, health) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""));
if run == "exited" || run == "dead" {
let logs = self
.docker(&["logs", "--tail", "15", name], Duration::from_secs(30))
.map(|logs| self.hide_token(logs))
.unwrap_or_else(|error| format!("diagnostic logs unavailable: {error:#}"));
bail!("service {} exited:\n{}", svc.id, logs.trim());
}
if has_health {
if health == "healthy" {
return Ok(());
}
if health == "unhealthy" {
bail!("service {} is unhealthy", svc.id);
}
} else {
let mine: Vec<&PortMap> = maps
.iter()
.filter(|m| svc.ports.iter().any(|(_, c)| *c == m.container))
.collect();
if run == "running"
&& mine.iter().all(|m| {
std::net::TcpStream::connect_timeout(
&([127, 0, 0, 1], m.actual).into(),
Duration::from_secs(1),
)
.is_ok()
})
{
return Ok(());
}
}
if t0.elapsed() > limit {
bail!("service {} not ready after {}s", svc.id, limit.as_secs());
}
std::thread::sleep(Duration::from_millis(1000));
}
}
fn record_cleanup_warnings(
&self,
steps: &mut [StepResult],
cleanup: Vec<crate::cleanup::CleanupIncomplete>,
) {
for diagnostic in cleanup {
let warning = format!("warning: {diagnostic}");
eprintln!("local-ci: {warning}");
if let Some(last) = steps.last_mut() {
last.note = Some(match last.note.take() {
Some(note) => format!("{note}; {warning}"),
None => warning,
});
}
}
}
fn stop_services(&self, names: &[String], steps: &mut [StepResult]) {
let diagnostics = crate::cleanup::remove_tracked_containers(self.ctx, names);
if diagnostics.is_empty() {
let set: HashSet<&String> = names.iter().collect();
self.ctx.cancel.untrack_containers(&set);
}
self.record_cleanup_warnings(steps, diagnostics);
}
}
#[cfg(target_os = "macos")]
fn script_pipe(path: &Path) -> Result<(File, File)> {
use std::os::fd::FromRawFd;
use std::os::unix::ffi::OsStrExt;
let c = std::ffi::CString::new(path.as_os_str().as_bytes())?;
let _ = fs::remove_file(path);
unsafe {
if libc::mkfifo(c.as_ptr(), 0o600) < 0 {
return Err(std::io::Error::last_os_error()).context("cannot make the script pipe");
}
let r = libc::open(
c.as_ptr(),
libc::O_RDONLY | libc::O_NONBLOCK | libc::O_CLOEXEC,
);
let r_err = std::io::Error::last_os_error();
let w = if r >= 0 {
libc::open(
c.as_ptr(),
libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC,
)
} else {
-1
};
let w_err = std::io::Error::last_os_error();
let _ = libc::unlink(c.as_ptr());
if r < 0 || w < 0 {
if r >= 0 {
libc::close(r);
}
if w >= 0 {
libc::close(w);
}
return Err(if r < 0 { r_err } else { w_err }).context("cannot open the script pipe");
}
let fl = libc::fcntl(r, libc::F_GETFL);
if fl < 0 || libc::fcntl(r, libc::F_SETFL, fl & !libc::O_NONBLOCK) < 0 {
let e = std::io::Error::last_os_error();
libc::close(r);
libc::close(w);
return Err(e).context("cannot set up the script pipe");
}
Ok((File::from_raw_fd(r), File::from_raw_fd(w)))
}
}
#[cfg(not(target_os = "macos"))]
fn script_pipe(_path: &Path) -> Result<(File, File)> {
use std::os::fd::{AsRawFd, OwnedFd};
let (r, w) = std::io::pipe().context("cannot make the script pipe")?;
let w = File::from(OwnedFd::from(w));
unsafe {
let fl = libc::fcntl(w.as_raw_fd(), libc::F_GETFL);
if fl < 0 || libc::fcntl(w.as_raw_fd(), libc::F_SETFL, fl | libc::O_NONBLOCK) < 0 {
return Err(std::io::Error::last_os_error()).context("cannot set up the script pipe");
}
}
Ok((File::from(OwnedFd::from(r)), w))
}
fn write_until_stopped(mut w: File, data: &[u8], stop: &AtomicBool) {
let mut rest = data;
while !rest.is_empty() && !stop.load(Ordering::SeqCst) {
match w.write(rest) {
Ok(0) => return,
Ok(n) => rest = &rest[n..],
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(5))
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(_) => return,
}
}
}
fn write_private(path: &Path, content: &str) -> std::io::Result<()> {
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
let mut f = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.mode(0o600)
.open(path)?;
fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
f.write_all(content.as_bytes())
}
struct OsLeg {
os: Option<(os_legs::Family, String)>,
twin: Option<String>,
}
fn record(
ctx: &mut Map<String, Value>,
id: &Option<String>,
outcome: &str,
conclusion: &str,
outputs: Map<String, Value>,
) {
if let Some(id) = id {
ctx.insert(
id.clone(),
json!({"outcome": outcome, "conclusion": conclusion, "outputs": outputs}),
);
}
}
pub fn write_json(path: &Path, v: &impl Serialize) -> Result<()> {
let mut f = File::create(path)?;
f.write_all(serde_json::to_string_pretty(v)?.as_bytes())?;
Ok(())
}
fn ensure_container_id(id: &str) -> Result<()> {
anyhow::ensure!(
crate::cleanup::valid_container_id(id),
"Docker did not acknowledge a complete container ID"
);
Ok(())
}
#[cfg(test)]
pub(crate) mod finalization_test {
type Probe = Box<dyn FnMut(&str)>;
std::thread_local! {
static PROBE: std::cell::RefCell<Option<Probe>> = const { std::cell::RefCell::new(None) };
}
pub(crate) fn inspect(boundary: &str) {
PROBE.with_borrow_mut(|probe| {
if let Some(probe) = probe {
probe(boundary);
}
});
}
pub(crate) fn observe<T>(probe: impl FnMut(&str) + 'static, action: impl FnOnce() -> T) -> T {
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
PROBE.with_borrow_mut(|probe| *probe = None);
}
}
PROBE.with_borrow_mut(|slot| {
assert!(slot.is_none());
*slot = Some(Box::new(probe));
});
let _reset = Reset;
action()
}
}
#[cfg(test)]
#[allow(clippy::disallowed_methods)] mod tests {
use super::*;
use std::process::Command;
#[test]
fn fresh_git_runners_share_process_resource_sequence() {
let area = tempfile::Builder::new()
.prefix("localci-resource-sequence-")
.tempdir_in(fs::canonicalize(std::env::temp_dir()).unwrap())
.unwrap();
let root = area.path();
fs::create_dir_all(root.join(".github/workflows")).unwrap();
fs::write(root.join(".github/workflows/ci.yml"),
"on: push\njobs:\n check:\n runs-on: fixture\n steps:\n - run: echo fixture\n").unwrap();
for args in [
vec!["init", "-q", "-b", "main"],
vec!["add", "."],
vec!["commit", "-qm", "fixture"],
] {
let status = Command::new("/usr/bin/git")
.args([
"-c",
"user.name=fixture",
"-c",
"user.email=fixture@example.invalid",
"-c",
"commit.gpgsign=false",
])
.args(args)
.current_dir(root)
.env_clear()
.env("PATH", "/usr/bin:/bin")
.env("HOME", root)
.env("GIT_CONFIG_NOSYSTEM", "1")
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.status()
.unwrap();
assert!(status.success());
}
let ctx = ExecContext::new(
[
("PATH".into(), "/usr/bin:/bin".into()),
("HOME".into(), root.display().to_string()),
]
.into(),
);
let other_ctx = ctx.fresh_attempt();
let fp = crate::build_frozen_plan(
&ctx,
&crate::Target {
dir: root.into(),
sha: "HEAD".into(),
base: Some("HEAD".into()),
all: true,
include_disabled: true,
workflows_dirs: vec![],
workflows: vec![],
jobs: vec![],
},
&mut crate::Quiet,
)
.unwrap();
let workspace = |name: &str| Workspace {
root: root.join(name),
repo_root: root.into(),
run_dir: root.join(format!("{name}-run")),
tools: root.join(format!("{name}-tools")),
lock_file: root.join(format!("{name}-lock")),
};
let opts = || Opts {
parallel: 1,
traffic_controller: None,
executor: None,
portool: None,
containers: 1,
job_timeout_min: 1.,
keep: false,
trash: root.join("trash"),
all_os_legs: false,
};
let a = Runner::new(&ctx, &fp, &workspace("one"), opts()).unwrap();
let b = Runner::new(&other_ctx, &fp, &workspace("two"), opts()).unwrap();
let names = [a.resource_name(), b.resource_name(), a.resource_name()];
assert_eq!(names.iter().collect::<HashSet<_>>().len(), 3, "{names:?}");
assert!(Arc::ptr_eq(&a.seq, &b.seq));
let prefix = format!("local-ci-{}-", std::process::id());
let values: Vec<usize> = names
.iter()
.map(|n| n.strip_prefix(&prefix).unwrap().parse().unwrap())
.collect();
assert!(values.windows(2).all(|v| v[0] < v[1]));
assert_ne!(a.wt, b.wt);
assert_ne!(a.run_dir, b.run_dir);
}
#[test]
fn run_label_plain() {
assert_eq!(
run_label("CI", "build", "Run tests"),
"CI / build / Run tests"
);
}
#[test]
fn run_label_matrix_job() {
assert_eq!(
run_label("CI", "test (ubuntu, 20)", "step 3"),
"CI / test (ubuntu, 20) / step 3"
);
}
#[test]
fn run_label_unnamed_step() {
assert_eq!(run_label("CI", "lint", "step 8"), "CI / lint / step 8");
}
#[test]
fn run_label_truncates_step_first() {
let l = run_label("CI", "build", &"x".repeat(200));
assert_eq!(l.chars().count(), RUN_LABEL_MAX);
assert!(l.starts_with("CI / build / xxx"));
assert!(l.ends_with('…'));
}
#[test]
fn run_label_long_front_is_cut_and_one_line() {
let l = run_label(&"w".repeat(80), &"j".repeat(80), "a\nb");
assert_eq!(l.chars().count(), RUN_LABEL_MAX);
assert_eq!(run_label("CI", "j", "a\n b"), "CI / j / a b");
}
#[test]
fn the_script_pipe_has_cloexec_a_nonblocking_writer_and_no_name_left() {
use std::os::fd::AsRawFd;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("p.fifo");
let (r, w) = script_pipe(&path).unwrap();
assert!(!path.exists());
for f in [&r, &w] {
let fl = unsafe { libc::fcntl(f.as_raw_fd(), libc::F_GETFD) };
assert!(fl >= 0 && fl & libc::FD_CLOEXEC != 0, "{fl}");
}
let (rl, wl) = unsafe {
(
libc::fcntl(r.as_raw_fd(), libc::F_GETFL),
libc::fcntl(w.as_raw_fd(), libc::F_GETFL),
)
};
assert_eq!(rl & libc::O_NONBLOCK, 0);
assert_ne!(wl & libc::O_NONBLOCK, 0);
let mut r = r;
let stop = AtomicBool::new(false);
write_until_stopped(w, b"abc", &stop);
let mut got = String::new();
r.read_to_string(&mut got).unwrap();
assert_eq!(got, "abc");
}
#[test]
fn the_writer_ends_with_the_step_even_if_a_reader_outlives_it() {
let dir = tempfile::tempdir().unwrap();
let (r, w) = script_pipe(&dir.path().join("p.fifo")).unwrap();
let stop = Arc::new(AtomicBool::new(false));
let big = vec![b'x'; 4 << 20];
let s2 = stop.clone();
let h = std::thread::spawn(move || write_until_stopped(w, &big, &s2));
std::thread::sleep(Duration::from_millis(300));
assert!(!h.is_finished());
stop.store(true, Ordering::SeqCst);
let t = Instant::now();
h.join().unwrap();
assert!(t.elapsed() < Duration::from_secs(2));
drop(r);
}
#[test]
fn the_writer_ends_when_every_reader_is_gone() {
let dir = tempfile::tempdir().unwrap();
let (r, w) = script_pipe(&dir.path().join("p.fifo")).unwrap();
drop(r);
let stop = AtomicBool::new(false);
write_until_stopped(w, &vec![b'x'; 1 << 20], &stop);
}
fn job_with_secs(secs: f64) -> JobResult {
JobResult {
workflow: "ci.yml".into(),
job: "j".into(),
display: "j".into(),
outcome: Outcome::Pass,
secs,
steps: vec![],
cancelled: false,
time: None,
build_cache: None,
os_note: None,
}
}
#[test]
fn a_units_waits_are_charged_to_its_first_job_once() {
let mut jobs = vec![job_with_secs(5.0), job_with_secs(7.0)];
charge(
&mut jobs,
UnitWait {
lock: 30.0,
parallel: 2.0,
..UnitWait::default()
},
);
assert_eq!(
jobs[0].time,
Some(JobTime {
work_secs: 5.0,
wait_lock_secs: 30.0,
wait_parallel_secs: 2.0,
..JobTime::default()
})
);
assert_eq!(jobs[1].time, None);
let mut jobs = vec![job_with_secs(5.0)];
charge(&mut jobs, UnitWait::default());
assert_eq!(jobs[0].time, None);
let mut ran = job_with_secs(3.0);
ran.time = Some(JobTime {
work_secs: 3.0,
..JobTime::default()
});
let mut jobs = vec![job_with_secs(0.0), ran];
charge(
&mut jobs,
UnitWait {
lock: 4.0,
parallel: 0.0,
..UnitWait::default()
},
);
assert_eq!(jobs[0].time, None);
assert_eq!(jobs[1].time.as_ref().unwrap().wait_lock_secs, 4.0);
}
#[test]
fn job_time_stamps_are_serialized_and_old_results_without_them_parse() {
let t = JobTime {
work_secs: 1.0,
requested_at_ms: 1_700_000_000_000,
started_at_ms: 1_700_000_001_000,
finished_at_ms: 1_700_000_002_000,
..JobTime::default()
};
let v = serde_json::to_value(&t).unwrap();
assert_eq!(v["requested_at_ms"], 1_700_000_000_000u64);
assert_eq!(v["started_at_ms"], 1_700_000_001_000u64);
assert_eq!(v["finished_at_ms"], 1_700_000_002_000u64);
assert_eq!(serde_json::from_value::<JobTime>(v).unwrap(), t);
let old: JobTime = serde_json::from_str(
r#"{"work_secs":2.0,"wait_lock_secs":0.0,"wait_slot_secs":0.0,"wait_queue_secs":0.0,"wait_parallel_secs":0.0}"#,
)
.unwrap();
assert_eq!(old.work_secs, 2.0);
assert_eq!(
(old.requested_at_ms, old.started_at_ms, old.finished_at_ms),
(0, 0, 0)
);
}
#[test]
fn a_unit_stamps_the_request_time_on_every_job_that_ran() {
let ran = |at: u64| {
let mut j = job_with_secs(1.0);
j.time = Some(JobTime {
work_secs: 1.0,
requested_at_ms: at,
started_at_ms: 5_000,
..JobTime::default()
});
j
};
let mut jobs = vec![ran(0), ran(4_000), job_with_secs(0.0)];
charge(
&mut jobs,
UnitWait {
requested_at_ms: 1_000,
..UnitWait::default()
},
);
assert_eq!(jobs[0].time.as_ref().unwrap().requested_at_ms, 1_000);
assert_eq!(jobs[1].time.as_ref().unwrap().requested_at_ms, 1_000);
assert_eq!(jobs[2].time, None);
}
#[test]
fn job_time_is_added_to_the_json_and_left_out_when_unknown() {
let mut j = job_with_secs(5.0);
let v = serde_json::to_value(&j).unwrap();
assert!(v.get("time").is_none(), "{v}");
assert_eq!(v["secs"], 5.0);
j.time = Some(JobTime {
work_secs: 4.0,
wait_queue_secs: 1.0,
..JobTime::default()
});
let v = serde_json::to_value(&j).unwrap();
assert_eq!(v["time"]["work_secs"], 4.0);
assert_eq!(v["time"]["wait_queue_secs"], 1.0);
assert_eq!(v["time"]["wait_slot_secs"], 0.0);
}
#[test]
fn file_commands() {
let v = parse_file_command("a=1\nmatrix<<EOF\n{\"x\":\n[1]}\nEOF\nb=two=2\n");
assert_eq!(
v,
vec![
("a".into(), "1".into()),
("matrix".into(), "{\"x\":\n[1]}".into()),
("b".into(), "two=2".into())
]
);
}
#[test]
fn port_rewrites() {
let maps = vec![PortMap {
declared: Some(5433),
container: 5432,
actual: 49152,
}];
assert_eq!(
rewrite_ports("postgresql://u:p@localhost:5433/db?x=1", &maps),
"postgresql://u:p@localhost:49152/db?x=1"
);
assert_eq!(rewrite_ports("127.0.0.1:54330", &maps), "127.0.0.1:54330");
assert_eq!(rewrite_env_value("DB_PORT", "5433", &maps), "49152");
assert_eq!(rewrite_env_value("COUNT", "5433", &maps), "5433");
assert_eq!(
rewrite_ports("TEST_DB_PORT=5433 docker compose up; N=5433", &maps),
"TEST_DB_PORT=49152 docker compose up; N=5433"
);
assert_eq!(rewrite_ports("PORT='5433' x", &maps), "PORT='49152' x");
}
#[test]
fn service_ports_the_workflow_never_names() {
let wf = |env: &str, run: &str| {
crate::workflow::parse(
"ci.yml",
&format!(
"on: push\njobs:\n t:\n runs-on: ubuntu-latest\n env: {{{env}}}\n services:\n db:\n image: mysql\n ports: ['15306:3306']\n steps:\n - run: {run}\n"
),
)
.unwrap()
};
let named = |w: &Workflow| rewritable_mention(w, &w.jobs[0], 15306);
assert!(!named(&wf("", "npm test")));
assert!(!named(&wf("COUNT: '15306'", "mysql -P 15306")));
assert!(named(&wf("DB_PORT: '15306'", "npm test")));
assert!(named(&wf(
"",
"DATABASE_URL=mysql://localhost:15306/x npm test"
)));
assert!(named(&wf(
"",
"PORT=${{ job.services.db.ports[3306] }} npm test"
)));
}
#[test]
fn fixed_ports_a_job_sets() {
assert!(port_key("PORT") && port_key("TEST_DB_PORT") && port_key("port_e2e"));
assert!(!port_key("EXPORT") && !port_key("REPORT") && !port_key("PORTS"));
assert_eq!(
assigned_ports("TEST_DB_PORT=15432 docker compose up\nEXPORT=4000 PORT=80 X=5000"),
vec![15432]
);
assert!(
assigned_ports("docker run -e POSTGRES_PORT=15432 --env=X_PORT=15433 img").is_empty()
);
let mut maps = vec![];
map_literals([15432, 15432, 15433], &mut maps).unwrap();
assert_eq!(maps.len(), 2);
assert_ne!(maps[0].actual, maps[1].actual);
assert_eq!(
rewrite_ports("docker run -e PGPORT=15432 img; PGPORT=15432", &maps[..1]),
format!("docker run -e PGPORT=15432 img; PGPORT={}", maps[0].actual)
);
assert_eq!(rewrite_env_value("REPORT", "15432", &maps), "15432");
assert!(maps
.iter()
.all(|m| m.actual != 0 && m.declared != Some(m.actual)));
}
#[test]
fn what_rewriting_cannot_reach() {
assert_eq!(
compose_files(
"docker compose -f a.yml --file=b.yml -p x up -d; docker compose -f \"$F\" up"
),
vec![Some("a.yml".into()), Some("b.yml".into()), None]
);
assert_eq!(compose_files("docker compose up -f nope").len(), 4);
assert!(compose_fixed("services:\n db:\n container_name: db\n"));
assert!(compose_fixed(" ports:\n - \"5432:5432\"\n"));
assert!(compose_fixed(" ports:\n - 127.0.0.1:5432:5432\n"));
assert!(compose_fixed(
" - target: 80\n published: 8080\n"
));
assert!(!compose_fixed(
" ports:\n - \"${DB_PORT:-5432}:5432\"\n - \"5432\"\n"
));
assert!(docker_run_fixed("docker run -d --name db postgres"));
assert!(docker_run_fixed("docker run \\\n -p 5432:5432 postgres"));
assert!(!docker_run_fixed(
"docker run -p 127.0.0.1::5432 -e X=1 postgres; docker compose run --name x web"
));
}
#[test]
fn ledger_timeouts_are_retried() {
let dir = tempfile::tempdir().unwrap();
let log = dir.path().join("step.log");
fs::write(&log, "earlier output\n").unwrap();
let from = fs::metadata(&log).unwrap().len();
let mut f = OpenOptions::new().append(true).open(&log).unwrap();
writeln!(f, "task-traffic-controller: waiting 0:00 (queue)").unwrap();
writeln!(
f,
"task-traffic-controller: ledger: timed out after 10s waiting for /x/ledger.lock"
)
.unwrap();
assert!(ledger_timed_out(&log, from));
writeln!(f, "npm ERR! something").unwrap();
assert!(!ledger_timed_out(&log, from));
assert!(!ledger_timed_out(&log, 0));
}
#[test]
fn only_the_commands_own_output_starts_its_clock() {
let p = "task-traffic-controller: waiting 0:08 (queue)";
assert!(!command_spoke(b""));
assert!(!command_spoke(format!("{p}\n{p}\n").as_bytes()));
assert!(!command_spoke(p.as_bytes()));
assert!(!command_spoke(format!("{p}\ntask-traffic").as_bytes()));
assert!(!command_spoke(format!("{p}\n{p}").as_bytes()));
assert!(command_spoke(format!("{p}\nhello\n").as_bytes()));
assert!(command_spoke(b"building..."));
assert!(command_spoke(format!("{p}\n50%\r").as_bytes()));
assert!(command_spoke(b"\n"));
assert!(command_spoke(format!("{p}\n\n{p}\n").as_bytes()));
}
#[test]
fn only_the_controllers_prefix_marks_its_own_lines() {
let p = "task-traffic-controller";
assert!(is_controller_line(&format!("{p}: waiting 0:00 (queue)")));
assert!(is_ledger_timeout_line(&format!(
"{p}: ledger: timed out after 10s"
)));
assert!(!is_ledger_timeout_line(&format!("{p}: waiting")));
assert!(!is_controller_line("canirun: waiting"));
assert!(!is_ledger_timeout_line("canirun: ledger: timed out"));
assert!(!is_ledger_timeout_line("ledger: timed out"));
}
#[test]
fn compose_projects_get_a_tag() {
assert_eq!(
rename_compose_projects(
"TEST_DB_PORT=1 docker compose \\\n -p app-int \\\n -f a.yml up -d",
"lc1-2"
),
"TEST_DB_PORT=1 docker compose \\\n -p app-int-lc1-2 \\\n -f a.yml up -d"
);
assert_eq!(
rename_compose_projects(
"mkdir -p app && docker compose --project-name=app down",
"t"
),
"mkdir -p app && docker compose --project-name=app-t down"
);
assert_eq!(
rename_compose_projects("COMPOSE_PROJECT_NAME=\"z\" docker compose up", "t"),
"COMPOSE_PROJECT_NAME=\"z-t\" docker compose up"
);
assert_eq!(
rename_compose_projects("docker compose -p a-t up", "t"),
"docker compose -p a-t up"
);
assert_eq!(
rename_compose_projects("docker compose -p a up\nnpm test -p b", "t"),
"docker compose -p a-t up\nnpm test -p b"
);
assert_eq!(
rename_compose_projects(
"docker compose -f x.yml -p a exec db mkdir -p tmp; docker compose run -p 8080:80 web",
"t"
),
"docker compose -f x.yml -p a-t exec db mkdir -p tmp; docker compose run -p 8080:80 web"
);
assert_eq!(
compose_projects("docker compose exec db psql -p 5432"),
Vec::<String>::new()
);
}
#[test]
fn compose_project_names() {
assert_eq!(
compose_projects(
"docker compose -p a up -d; docker compose -p b down; docker compose -p a ps"
),
vec!["a", "b"]
);
assert_eq!(
compose_projects("TEST_DB_PORT=1 docker compose \\\n -p app-int \\\n -f a.yml up -d"),
vec!["app-int"]
);
assert_eq!(
compose_projects("docker compose --project-name=y up"),
vec!["y"]
);
assert!(compose_projects("npm run test -p foo").is_empty());
assert!(compose_projects("mkdir -p api && docker compose up -d").is_empty());
assert_eq!(
compose_projects("COMPOSE_PROJECT_NAME=z docker compose up"),
vec!["z"]
);
}
#[test]
fn npm_installs_once_per_directory() {
let tmp = tempfile::tempdir().unwrap();
let log = tmp.path().join("calls");
let fake = tmp.path().join("fake-npm");
crate::fake_exec::write_executable(
&fake,
format!(
"#!/bin/sh\necho \"$*\" >> {}\nmkdir -p node_modules\n",
log.display()
),
0o755,
);
let shim = tmp.path().join("npm");
crate::fake_exec::write_executable(
&shim,
NPM_SHIM.replace("__REAL__", &fake.to_string_lossy()),
0o755,
);
let ws = tmp.path().join("ws");
let proj = ws.join("proj");
fs::create_dir_all(&proj).unwrap();
fs::write(proj.join("package-lock.json"), "{}").unwrap();
let npm_in = |ws: &Path, marks: &str, args: &[&str]| {
let st = Command::new(&shim)
.args(args)
.current_dir(ws.join("proj"))
.env("GITHUB_WORKSPACE", ws)
.env("LOCAL_CI_MARKS", tmp.path().join(marks))
.stderr(Stdio::null())
.status()
.unwrap();
assert!(st.success());
};
let npm = |args: &[&str]| npm_in(&ws, "marks", args);
npm(&["ci", "--no-audit"]);
npm(&["ci"]);
npm(&["install"]);
npm(&["install", "left-pad"]);
npm(&["run", "test"]);
fs::write(proj.join("package-lock.json"), "{\"changed\":1}").unwrap();
npm(&["ci"]);
let calls = fs::read_to_string(&log).unwrap();
assert_eq!(calls, "ci --no-audit\ninstall left-pad\nrun test\nci\n");
let copy = tmp.path().join("copy");
fs::create_dir_all(copy.join("proj/node_modules")).unwrap();
fs::copy(
proj.join("package-lock.json"),
copy.join("proj/package-lock.json"),
)
.unwrap();
fs::create_dir_all(tmp.path().join("copied-marks")).unwrap();
for e in fs::read_dir(tmp.path().join("marks")).unwrap().flatten() {
if e.file_type().unwrap().is_file() {
fs::copy(
e.path(),
tmp.path().join("copied-marks").join(e.file_name()),
)
.unwrap();
}
}
npm_in(©, "copied-marks", &["ci"]);
npm_in(©, "other-marks", &["ci"]);
let calls = fs::read_to_string(&log).unwrap();
assert_eq!(calls, "ci --no-audit\ninstall left-pad\nrun test\nci\nci\n");
let shared = tmp.path().join("setup/node_modules");
fs::create_dir_all(shared.join("x")).unwrap();
fs::write(shared.join("x/index.js"), "x").unwrap();
let linked = tmp.path().join("linked");
let nm = linked.join("proj/node_modules");
fs::create_dir_all(&nm).unwrap();
fs::write(linked.join("proj/package-lock.json"), "{}").unwrap();
std::os::unix::fs::symlink(shared.join("x"), nm.join("x")).unwrap();
fs::write(
nm.join(crate::git::SHARED),
shared.to_string_lossy().as_bytes(),
)
.unwrap();
npm_in(&linked, "copied-marks", &["run", "test"]);
assert!(nm.join("x").is_symlink());
npm_in(&linked, "copied-marks", &["rebuild"]);
assert!(!nm.join("x").is_symlink() && !nm.join(crate::git::SHARED).exists());
assert_eq!(fs::read_to_string(nm.join("x/index.js")).unwrap(), "x");
assert!(shared.join("x/index.js").is_file());
assert!(!linked.join("proj/.node_modules.local-ci").exists());
}
#[test]
fn steps_that_write_node_modules() {
assert!(writes_node_modules("npx prisma generate"));
assert!(writes_node_modules("cd api && npm ci"));
assert!(writes_node_modules("npm i -D left-pad"));
assert!(writes_node_modules("yarn install --frozen-lockfile"));
assert!(!writes_node_modules("npm run test"));
assert!(!writes_node_modules("npm init -y"));
assert!(!writes_node_modules("npx prisma migrate deploy"));
}
#[test]
fn ansi_and_slugs() {
assert_eq!(strip_ansi("\x1b[31mred\x1b[0m\r"), "red");
assert_eq!(
slug_of("Run integration tests (1/2)"),
"run-integration-tests-1-2"
);
}
#[test]
fn a_task_result_survives_a_round_trip_through_json() {
let step = |o: Outcome, note: Option<&str>| StepResult {
label: "step".into(),
outcome: o,
exit: Some(1),
secs: 1.5,
log: Some(PathBuf::from("/l/log")),
note: note.map(String::from),
};
let job = |display: &str, o: Outcome, cancelled: bool, time: Option<JobTime>| JobResult {
workflow: "ci.yml".into(),
job: "j".into(),
display: display.into(),
outcome: o,
secs: 2.0,
steps: vec![
step(Outcome::Pass, Some("a note")),
step(Outcome::Fail, None),
],
cancelled,
time,
build_cache: None,
os_note: (display == "c").then(|| "ran on macOS, not Linux (runs-on x)".to_string()),
};
let time = JobTime {
work_secs: 1.0,
wait_lock_secs: 2.0,
wait_slot_secs: 3.0,
wait_queue_secs: 4.0,
wait_parallel_secs: 5.0,
requested_at_ms: 1_700_000_000_000,
started_at_ms: 1_700_000_001_000,
finished_at_ms: 1_700_000_009_000,
};
let r = crate::task::TaskResult {
schema_version: crate::wire::wire_version(),
task: "t1".into(),
jobs: vec![
job("a", Outcome::Pass, false, Some(time.clone())),
job("b", Outcome::Fail, true, None),
job("c", Outcome::Skip("why".into()), false, None),
job("d", Outcome::Error("boom".into()), false, None),
],
outcomes: vec![crate::task::JobOutcome {
job: "j".into(),
variant: Some(1),
status: crate::task::JobStatus::Success,
outputs: [("k".to_string(), "v".to_string())].into(),
skipped: None,
ancestor_failed: true,
}],
receipt_ignored: Some("another commit".into()),
artifacts: vec!["bundle".into()],
shard: None,
};
let text = serde_json::to_string(&r).unwrap();
let back: crate::task::TaskResult = serde_json::from_str(&text).unwrap();
assert_eq!(serde_json::to_string(&back).unwrap(), text);
assert_eq!(back.jobs[0].time, Some(time));
assert_eq!(back.jobs[1].outcome, Outcome::Fail);
assert!(back.jobs[1].cancelled && !back.jobs[0].cancelled);
assert_eq!(back.jobs[2].outcome, Outcome::Skip("why".into()));
assert_eq!(back.jobs[3].outcome, Outcome::Error("boom".into()));
assert_eq!(
back.jobs[2].os_note.as_deref(),
Some("ran on macOS, not Linux (runs-on x)")
);
assert_eq!(back.jobs[0].os_note, None);
assert_eq!(back.jobs[0].steps[0].note.as_deref(), Some("a note"));
assert_eq!(back.jobs[0].steps[1].note, None);
assert_eq!(back.artifacts, ["bundle"]);
}
}