use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::{mpsc, oneshot};
use crate::receipt::now_ms;
use crate::script::shell_quote;
use crate::transport::{Transport, TransportError, LINE_QUEUE, SCRIPT_LINE_LIMIT, STEP_LINE_LIMIT};
const RECONNECT_DELAYS: [Duration; 4] = [
Duration::from_secs(1),
Duration::from_secs(2),
Duration::from_secs(4),
Duration::from_secs(8),
];
const MAX_REATTACHES: usize = 5;
pub(crate) const LOG_START: &str = "shipslip-log-start";
pub(crate) const ALIVE: &str = "shipslip-alive-";
const ALIVE_INTERVAL_SECS: u64 = 5;
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum StepResult {
Exited(i32),
NotStarted(String),
Gone,
Interrupted(String),
}
#[derive(Debug, PartialEq, Eq)]
enum Probe {
Exited(i32),
Running,
Gone,
NotStarted,
}
pub(crate) enum ConnectionChange {
Lost { at_ms: u128, detail: String },
Reattached { at_ms: u128 },
}
pub(crate) enum Observed {
Line(String),
Drained(oneshot::Sender<()>),
}
pub(crate) struct Connection<'a> {
reattaches: usize,
lost: bool,
heard_at_ms: u128,
pub result_seen_at_ms: Option<u128>,
notify: &'a (dyn Fn(ConnectionChange) -> Result<(), String> + Sync),
}
impl<'a> Connection<'a> {
pub fn new(notify: &'a (dyn Fn(ConnectionChange) -> Result<(), String> + Sync)) -> Self {
Self {
reattaches: 0,
lost: false,
heard_at_ms: now_ms(),
result_seen_at_ms: None,
notify,
}
}
fn heard(&mut self) {
self.heard_at_ms = now_ms();
}
fn reattached(&mut self, probe: &Probe) -> Result<(), StepResult> {
if self.lost {
let at_ms = now_ms();
if matches!(probe, Probe::Exited(_)) {
self.result_seen_at_ms.get_or_insert(at_ms);
}
(self.notify)(ConnectionChange::Reattached { at_ms })
.map_err(StepResult::Interrupted)?;
self.lost = false;
}
Ok(())
}
}
fn run_dir(run_id: &str) -> String {
format!("\"$HOME\"/.shipslip/runs/{}", shell_quote(run_id))
}
const IDENT_FN: &str = r#"ident() { s=$(cat "/proc/$1/stat" 2>/dev/null) || return 0; s=${s##*) }; set -- $s; echo "$(cat /proc/sys/kernel/random/boot_id 2>/dev/null) ${20}"; }"#;
const SAME_PROCESS_FN: &str = r#"same_process() { [ ! -s "$d/ident" ] || [ "$(ident "$(cat "$d/pid")")" = "$(cat "$d/ident")" ]; }"#;
pub(crate) fn launch_script(run_id: &str, key: &str, script: &str) -> String {
format!(
r#"set -e
recipe_umask=$(umask)
umask 077
mkdir -p {runs}
chmod 700 "$HOME"/.shipslip "$HOME"/.shipslip/runs
printf '%s' {script} > {runs}/{key}.sh
mkdir {runs}/{key}
d={runs}/{key}
mv "$d.sh" "$d/script.sh"
setsid nohup bash -c 'echo $$ > "$1/pid.tmp" && mv "$1/pid.tmp" "$1/pid"; (umask "$2"; bash -l -s < "$1/script.sh"); echo $? > "$1/exit.tmp"; mv "$1/exit.tmp" "$1/exit"' _ "$d" "$recipe_umask" > "$d/log" 2>&1 < /dev/null &
{ident}
for _ in $(seq 100); do
if [ -s "$d/pid" ]; then
ident "$(cat "$d/pid")" > "$d/ident.tmp" && mv "$d/ident.tmp" "$d/ident"
exit 0
fi
sleep 0.05
done
exit 1
"#,
runs = run_dir(run_id),
script = shell_quote(script),
ident = IDENT_FN,
)
}
pub(crate) fn observe_script(run_id: &str, key: &str, skip: usize, alive: &str) -> String {
format!(
r#"d={runs}/{key}
echo {LOG_START}
{ident}
{same_process}
same_process || exec tail -n +{from} "$d/log" 2>/dev/null
(while sleep {ALIVE_INTERVAL_SECS} </dev/null >/dev/null 2>&1; do echo {alive} >&2 || exit; done) </dev/null >/dev/null &
alive=$!
tail -n +{from} -s 0.2 --pid="$(cat "$d/pid")" -f "$d/log" 2>/dev/null
status=$?
kill "$alive" 2>/dev/null
exit "$status"
"#,
runs = run_dir(run_id),
from = skip + 1,
ident = IDENT_FN,
same_process = SAME_PROCESS_FN,
)
}
fn alive_marker() -> String {
static SEQ: AtomicU64 = AtomicU64::new(0);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or_default();
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
format!("{ALIVE}{nanos:x}-{:x}-{seq:x}", std::process::id())
}
pub(crate) fn probe_script(run_id: &str, key: &str) -> String {
format!(
r#"d={runs}/{key}
{ident}
{same_process}
state() {{
if [ -e "$d/exit" ]; then echo "exited $(cat "$d/exit")"
elif [ ! -d "$d" ]; then echo not-started
elif [ -s "$d/pid" ] && kill -0 "$(cat "$d/pid")" 2>/dev/null && same_process; then echo running
else return 1
fi
}}
state || {{ sleep 1; state || echo gone; }}
"#,
runs = run_dir(run_id),
ident = IDENT_FN,
same_process = SAME_PROCESS_FN,
)
}
fn parse_probe(lines: &[String]) -> Option<Probe> {
let last = lines.iter().rev().find(|l| !l.trim().is_empty())?.trim();
match last {
"running" => Some(Probe::Running),
"gone" => Some(Probe::Gone),
"not-started" => Some(Probe::NotStarted),
_ => last
.strip_prefix("exited ")?
.parse()
.ok()
.map(Probe::Exited),
}
}
pub(crate) async fn launch_step<T: Transport>(
transport: &T,
run_id: &str,
key: &str,
script: &str,
connection: &mut Connection<'_>,
) -> Result<(), StepResult> {
let (launch, launch_output) = run_collect(transport, &launch_script(run_id, key, script)).await;
if launch.is_ok() {
connection.heard();
}
if let Err(e @ TransportError::Connect(_)) = &launch {
return Err(StepResult::NotStarted(e.to_string()));
}
if launch != Ok(0) {
let mut last = launch.clone();
loop {
if let Err(reason) = reconnect_if_lost(transport, &last, connection, None).await {
return Err(StepResult::Interrupted(reason));
}
let (result, lines) = run_collect(transport, &probe_script(run_id, key)).await;
if result.is_err() {
last = result;
continue;
}
let probe = parse_probe(&lines).ok_or_else(|| unexpected(&lines))?;
connection.reattached(&probe)?;
match probe {
Probe::NotStarted => {
return Err(StepResult::NotStarted(match &launch {
Err(e) => e.to_string(),
Ok(code) => {
format!("launcher exited with {code}: {}", launch_output.join("\n"))
}
}))
}
_ => break,
}
}
}
Ok(())
}
pub(crate) async fn attach_step<T: Transport>(
transport: &T,
run_id: &str,
key: &str,
output: &mpsc::Sender<Observed>,
connection: &mut Connection<'_>,
) -> StepResult {
loop {
let (result, lines) = run_collect(transport, &probe_script(run_id, key)).await;
if let Err(reason) = reconnect_if_lost(transport, &result, connection, Some(output)).await {
return StepResult::Interrupted(reason);
}
if result.is_err() {
continue;
}
let Some(probe) = parse_probe(&lines) else {
return unexpected(&lines);
};
if let Err(result) = connection.reattached(&probe) {
return result;
}
match probe {
Probe::NotStarted => {
return StepResult::NotStarted(
"the step was not launched before Shipslip exited".into(),
)
}
Probe::Gone => return StepResult::Gone,
Probe::Running | Probe::Exited(_) => break,
}
}
follow_existing(transport, run_id, key, output, connection).await
}
pub(crate) async fn follow_existing<T: Transport>(
transport: &T,
run_id: &str,
key: &str,
output: &mpsc::Sender<Observed>,
connection: &mut Connection<'_>,
) -> StepResult {
let mut seen = 0;
loop {
if connection.lost {
let (result, lines) = run_collect(transport, &probe_script(run_id, key)).await;
if let Err(reason) =
reconnect_if_lost(transport, &result, connection, Some(output)).await
{
return StepResult::Interrupted(reason);
}
if result.is_err() {
continue;
}
let Some(probe) = parse_probe(&lines) else {
return unexpected(&lines);
};
if let Err(result) = connection.reattached(&probe) {
return result;
}
}
let observed = observe(transport, run_id, key, &mut seen, output, connection).await;
if let Err(reason) = reconnect_if_lost(transport, &observed, connection, Some(output)).await
{
return StepResult::Interrupted(reason);
}
if observed.is_err() {
continue;
}
let (result, lines) = run_collect(transport, &probe_script(run_id, key)).await;
if let Err(reason) = reconnect_if_lost(transport, &result, connection, Some(output)).await {
return StepResult::Interrupted(reason);
}
if result.is_err() {
continue;
}
match parse_probe(&lines) {
Some(Probe::Exited(code)) => return StepResult::Exited(code),
Some(Probe::Gone) => return StepResult::Gone,
Some(Probe::Running | Probe::NotStarted) => {
connection.reattaches += 1;
if connection.reattaches > MAX_REATTACHES {
return StepResult::Interrupted("could not follow the step's output".into());
}
}
None => return unexpected(&lines),
}
}
}
fn unexpected(lines: &[String]) -> StepResult {
StepResult::Interrupted(format!(
"unexpected status from the server: {}",
lines.join("\n")
))
}
pub(crate) async fn run_collect<T: Transport>(
transport: &T,
script: &str,
) -> (Result<i32, TransportError>, Vec<String>) {
run_collect_each(transport, script, |_| {}).await
}
pub(crate) async fn run_collect_each<T: Transport>(
transport: &T,
script: &str,
mut each: impl FnMut(&str),
) -> (Result<i32, TransportError>, Vec<String>) {
let (tx, mut rx) = mpsc::channel::<String>(LINE_QUEUE);
let collect = async {
let mut lines = Vec::new();
while let Some(line) = rx.recv().await {
each(&line);
lines.push(line);
}
lines
};
tokio::join!(transport.run(script, tx, SCRIPT_LINE_LIMIT), collect)
}
async fn observe<T: Transport>(
transport: &T,
run_id: &str,
key: &str,
seen: &mut usize,
output: &mpsc::Sender<Observed>,
connection: &mut Connection<'_>,
) -> Result<i32, TransportError> {
let alive = alive_marker();
let script = observe_script(run_id, key, *seen, &alive);
let (tx, mut rx) = mpsc::channel(LINE_QUEUE);
let forward = async {
let mut started = false;
while let Some(line) = rx.recv().await {
connection.heard();
if line == alive {
continue;
}
if !started {
started = line == LOG_START;
continue;
}
*seen += 1;
let _ = output.send(Observed::Line(line)).await;
}
};
let (result, ()) = tokio::join!(transport.run(&script, tx, STEP_LINE_LIMIT), forward);
result
}
async fn reconnect_if_lost<T: Transport>(
transport: &T,
result: &Result<i32, TransportError>,
connection: &mut Connection<'_>,
output: Option<&mpsc::Sender<Observed>>,
) -> Result<(), String> {
let Err(err) = result else {
connection.heard();
return Ok(());
};
if !connection.lost {
let at_ms = connection.heard_at_ms;
if let Some(output) = output {
let (acknowledge, drained) = oneshot::channel();
let _ = output.send(Observed::Drained(acknowledge)).await;
let _ = drained.await;
}
(connection.notify)(ConnectionChange::Lost {
at_ms,
detail: err.to_string(),
})?;
connection.lost = true;
}
connection.reattaches += 1;
if connection.reattaches > MAX_REATTACHES {
return Err(err.to_string());
}
let mut last = err.to_string();
for delay in RECONNECT_DELAYS {
tokio::time::sleep(delay).await;
match transport.reconnect().await {
Ok(()) => return Ok(()),
Err(e) => last = e.to_string(),
}
}
Err(last)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn launch_refuses_to_start_a_step_twice() {
let s = launch_script("r1", "step-2", "true");
let guard = s
.find("mkdir \"$HOME\"/.shipslip/runs/'r1'/step-2\n")
.unwrap();
assert!(guard < s.find("setsid").unwrap());
assert!(s.starts_with("set -e\n"));
}
#[test]
fn launch_embeds_the_script_quoted() {
let s = launch_script("r1", "step-0", "echo 'hi' \"$HOME\"");
assert!(s.contains(r#"printf '%s' 'echo '\''hi'\'' "$HOME"' >"#));
}
#[test]
fn observe_resumes_after_seen_lines() {
assert!(observe_script("r1", "step-1", 0, "x").contains("tail -n +1 "));
assert!(observe_script("r1", "step-1", 7, "x").contains("tail -n +8 "));
}
#[test]
fn probe_output_is_parsed_from_the_last_line() {
let lines = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(
parse_probe(&lines(&["motd", "exited 3"])),
Some(Probe::Exited(3))
);
assert_eq!(parse_probe(&lines(&["running", ""])), Some(Probe::Running));
assert_eq!(parse_probe(&lines(&["gone"])), Some(Probe::Gone));
assert_eq!(
parse_probe(&lines(&["not-started"])),
Some(Probe::NotStarted)
);
assert_eq!(parse_probe(&lines(&["exited x"])), None);
assert_eq!(parse_probe(&[]), None);
}
#[cfg(target_os = "linux")]
#[test]
fn a_reused_process_id_is_not_the_running_step() {
use std::process::Command;
use std::time::{Duration, Instant};
let home = std::env::temp_dir().join(format!("shipslip-runner-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&home);
std::fs::create_dir_all(&home).unwrap();
let run = |script: &str| {
let output = Command::new("bash")
.arg("-c")
.arg(script)
.env("HOME", &home)
.output()
.unwrap();
String::from_utf8_lossy(&output.stdout)
.lines()
.map(String::from)
.collect::<Vec<_>>()
};
let probe = || parse_probe(&run(&probe_script("r1", "step-1")));
let dir = home.join(".shipslip/runs/r1/step-1");
run(&launch_script("r1", "step-1", "echo hi; sleep 30"));
let pid = std::fs::read_to_string(dir.join("pid")).unwrap();
assert!(!std::fs::read_to_string(dir.join("ident"))
.unwrap()
.trim()
.is_empty());
assert_eq!(probe(), Some(Probe::Running));
std::fs::write(dir.join("ident"), "another-boot 1\n").unwrap();
assert_eq!(probe(), Some(Probe::Gone));
let started = Instant::now();
let observed = run(&observe_script("r1", "step-1", 0, &alive_marker()));
assert!(started.elapsed() < Duration::from_secs(10));
assert_eq!(observed.last().map(String::as_str), Some("hi"));
std::fs::remove_file(dir.join("ident")).unwrap();
assert_eq!(probe(), Some(Probe::Running));
let _ = Command::new("kill")
.arg("--")
.arg(format!("-{}", pid.trim()))
.status();
let _ = std::fs::remove_dir_all(&home);
}
}