use crate::protocol::{Outcome, Status};
use crate::{
WorkflowError,
artifact::{ArtifactRole, RunManifest, StorageLocation},
storage::{Store, atomic_json, run_id},
study::StudyPlan,
workspace::WorkspaceLease,
};
use serde::{Deserialize, Serialize};
use std::{
io,
path::{Path, PathBuf},
process::{Command, Stdio},
time::{Duration, Instant},
};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RunHandle {
pub run_id: String,
pub socket: PathBuf,
pub workspace: PathBuf,
pub host_id: String,
pub input: PathBuf,
pub storage: StorageLocation,
}
impl RunHandle {
pub fn client(&self) -> io::Result<crate::client::RunClient> {
crate::client::RunClient::connect(&self.socket)
}
pub fn wait(&self) -> io::Result<Status> {
match self.client().and_then(|c| c.wait()) {
Ok(status) => Ok(status),
Err(error) => {
let status: Status = Store::open(&self.storage)?
.json(&format!("{}/records/status.json", self.run_id))?;
if status.outcome.terminal() {
Ok(status)
} else {
Err(error)
}
}
}
}
}
#[derive(Serialize, Deserialize)]
pub(super) struct LaunchSpec {
pub handle: RunHandle,
pub input: PathBuf,
pub manifest: RunManifest,
pub max_bytes: u64,
pub path: std::ffi::OsString,
}
pub(crate) fn start(input: &Path) -> Result<RunHandle, WorkflowError> {
start_mode(input, false)
}
pub(super) fn start_mode(input: &Path, capture_only: bool) -> Result<RunHandle, WorkflowError> {
let input = input.canonicalize()?;
if input.join("campaign.json").is_file() {
let campaign = crate::campaign::CampaignPlan::load(&input)?;
campaign.check()?;
let software = campaign
.declaration
.studies
.iter()
.map(|m| {
if m.runner.is_absolute() {
m.runner.clone()
} else {
input.join(&m.runner)
}
})
.collect::<Vec<_>>();
return start_prepared(
&input,
campaign.settings,
software,
Vec::new(),
Default::default(),
None,
"campaign",
capture_only,
);
}
let study = StudyPlan::load(&input)?;
crate::runtime::check_prerequisites(&study)?;
let settings = study.runtime_settings().clone();
let verification = study
.verification()
.map(|v| v.resolve(&input))
.transpose()
.map_err(crate::study::StudyError::from)?;
let mut software = study
.phases()
.iter()
.flat_map(|p| p.tasks())
.flat_map(|t| [t.program_path(), t.python_script()].into_iter().flatten())
.map(Path::to_path_buf)
.collect::<Vec<_>>();
if let Some(program) = &verification {
software.push(program.program().to_path_buf());
if let Some(script) = program.python_script() {
software.push(script.to_path_buf());
}
}
let mut python = study
.phases()
.iter()
.flat_map(|p| p.tasks())
.filter_map(|t| t.program_declaration())
.filter(|p| p.capture_key().is_some())
.cloned()
.collect::<Vec<_>>();
if let Some(program) = verification
&& program.capture_key().is_some()
{
python.push(program);
}
start_prepared(
&input,
settings,
software,
python,
study.reproduction().clone(),
Some(study),
"study",
capture_only,
)
}
fn collision_id(id: &str) -> String {
let (base, sequence) = id.split_once('-').map_or((id, 0), |(base, sequence)| {
(base, sequence.parse::<u64>().unwrap_or(0))
});
format!("{base}-{:04}", sequence + 1)
}
struct StartupRecord {
store: Store,
root: PathBuf,
manifest: RunManifest,
armed: bool,
}
impl Drop for StartupRecord {
fn drop(&mut self) {
if !self.armed {
return;
}
if std::fs::File::open(self.root.join("records/status.json"))
.ok()
.and_then(|f| serde_json::from_reader::<_, Status>(f).ok())
.is_some_and(|s| s.outcome.terminal())
{
return;
}
self.manifest.outcome = Outcome::Failed;
let status = Status {
version: crate::protocol::VERSION,
run_id: self.manifest.run_id.clone(),
sequence: 0,
updated_at: crate::storage::utc_now(),
pid: std::process::id(),
outcome: Outcome::Failed,
pause_reason: None,
control: "finished".into(),
study: None,
tasks: Default::default(),
allocations: serde_json::json!({}),
message: Some(
"capture or engine startup failed; inspect the launch error and retained workspace"
.into(),
),
wall_ms: 0,
active_ms: 0,
};
let _ = atomic_json(&self.root.join("records/status.json"), &status);
let _ = self.store.put_json(
&format!("{}/records/status.json", self.manifest.run_id),
&status,
&self.root,
false,
);
let _ = self.store.put_json(
&format!("{}/manifest.json", self.manifest.run_id),
&self.manifest,
&self.root,
false,
);
let _ = crate::registry::index_manifest(&self.store, &self.manifest, &self.root);
}
}
#[allow(clippy::too_many_arguments)]
fn start_prepared(
input: &Path,
settings: crate::config::RuntimeSettings,
software: Vec<PathBuf>,
python: Vec<crate::config::ResolvedProgramTask>,
reproduction: crate::config::ReproductionSpecification,
expected: Option<StudyPlan>,
kind: &str,
capture_only: bool,
) -> Result<RunHandle, WorkflowError> {
let store = Store::open(&settings.storage)?;
let mut id = run_id();
let mut lease;
loop {
lease = match WorkspaceLease::create(&settings.workspace.root, &id) {
Ok(lease) => lease,
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
id = collision_id(&id);
continue;
}
Err(error) => return Err(error.into()),
};
let marker = serde_json::json!({"format":"scientific-workflow-reservation.v1","run_id":id});
match store.put_json(
&format!("{id}/reservation.json"),
&marker,
&lease.root,
true,
) {
Ok(()) => break,
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
id = collision_id(&id);
}
Err(e) => return Err(e.into()),
}
}
let root = lease.root.clone();
let initial = RunManifest {
format: "scientific-workflow-run.v1".into(),
run_id: id.clone(),
kind: kind.into(),
scientific_identity: crate::artifact::digest_bytes(b""),
artifacts: Default::default(),
capture_complete: false,
outcome: Outcome::Starting,
removed: Vec::new(),
};
let mut startup = StartupRecord {
store: store.clone(),
root: root.clone(),
manifest: initial,
armed: true,
};
store.put_json(
&format!("{id}/manifest.json"),
&startup.manifest,
&root,
false,
)?;
let _budget = crate::workspace::CaptureBudget::new(&root, settings.workspace.max_bytes.get())?;
let captured = root.join("inputs");
std::fs::create_dir(&captured)?;
let mut artifacts = Default::default();
crate::provenance::capture_tree(&store, input, "inputs", Some(&captured), &mut artifacts)?;
if let Some(expected) = expected {
expected
.verify_capture(&captured)
.map_err(crate::study::StudyError::from)?;
}
crate::workspace::check_capacity()?;
if crate::workspace::bytes(&root)? > settings.workspace.max_bytes.get() {
return Err(io::Error::other("captured input exceeds workspace budget").into());
}
let executable = std::env::current_exe()?.canonicalize()?;
let runner = root.join("reproduction/software/runner");
crate::provenance::capture_file(
&store,
&executable,
"reproduction/software/runner",
Some(&runner),
&mut artifacts,
ArtifactRole::Reproduction,
)?;
crate::provenance::capture_libraries(&store, &executable, &root, &mut artifacts)?;
let mut python_bindings = std::collections::BTreeMap::new();
for program in python {
if let Some(key) = program.capture_key()
&& python_bindings.contains_key(key)
{
continue;
}
if let Some((key, value)) =
crate::provenance::capture_python(&store, &program, &root, &mut artifacts)?
{
python_bindings.insert(key, value);
}
}
let mut bindings = std::collections::BTreeMap::new();
let numerical = crate::provenance::capture_environment(&reproduction.environment)?;
let mut input_bindings = std::collections::BTreeMap::new();
for (name, source) in reproduction.inputs {
crate::artifact::validate_key(&name)?;
let key = format!("reproduction/external-inputs/{name}");
if let Some(locator) = settings.input_bindings.get(&name) {
let selected = locator.open()?;
for reference in selected.references() {
let relative = reference
.key
.strip_prefix(&locator.prefix)
.ok_or_else(|| io::Error::other("input reference escapes its selection"))?;
let target = format!("{key}{relative}");
let copied = store.copy_reference(
&target,
selected.reader(relative.trim_start_matches('/'))?,
reference,
ArtifactRole::Reproduction,
)?;
artifacts.insert(target, copied);
}
} else {
let source = if source.is_absolute() {
source
} else {
input.join(source)
}
.canonicalize()?;
if source.is_dir() {
crate::provenance::capture_tree(&store, &source, &key, None, &mut artifacts)?;
} else {
crate::provenance::capture_file(
&store,
&source,
&key,
None,
&mut artifacts,
ArtifactRole::Reproduction,
)?;
}
}
input_bindings.insert(
name,
crate::artifact::ArtifactLocator {
storage: settings.storage.clone(),
run_id: id.clone(),
prefix: key,
},
);
}
for (i, source) in reproduction.software.into_iter().enumerate() {
let source = if source.is_absolute() {
source
} else {
input.join(source)
}
.canonicalize()?;
let key = format!(
"reproduction/software/declared-{i}/{}",
source
.file_name()
.ok_or_else(|| io::Error::other("software source requires a file or folder name"))?
.to_string_lossy()
);
let target = root.join(&key);
if source.is_dir() {
crate::provenance::capture_software_tree(
&store,
&source,
&key,
&target,
&mut artifacts,
)?;
} else {
crate::provenance::capture_file(
&store,
&source,
&key,
Some(&target),
&mut artifacts,
ArtifactRole::Reproduction,
)?;
crate::provenance::capture_libraries(&store, &source, &root, &mut artifacts)?;
}
bindings.insert(source, target);
}
for source in software {
let source = source.canonicalize()?;
if source
.strip_prefix(input)
.is_ok_and(|p| captured.join(p).is_file())
{
continue;
}
crate::provenance::capture_libraries(&store, &source, &root, &mut artifacts)?;
let digest = crate::artifact::digest_reader(std::fs::File::open(&source)?)?.0;
let key = format!(
"reproduction/software/{digest}/{}",
source.file_name().unwrap().to_string_lossy()
);
let local = root.join(&key);
if let std::collections::btree_map::Entry::Vacant(entry) = bindings.entry(source.clone()) {
crate::provenance::capture_file(
&store,
&source,
&key,
Some(&local),
&mut artifacts,
ArtifactRole::Reproduction,
)?;
entry.insert(local);
}
}
let effective = root.join("execution-input");
std::fs::create_dir(&effective)?;
copy_tree(&captured, &effective)?;
let runtime_path = effective.join(if kind == "campaign" {
"runtime.json"
} else {
"wf_configs/runtime.json"
});
let mut runtime: serde_json::Value =
serde_json::from_reader(std::fs::File::open(&runtime_path)?)?;
if kind == "study" {
runtime["input_bindings"] = serde_json::to_value(&input_bindings)?;
}
if let Some(environment) = python_bindings.get("standard-npy") {
let mut environment = environment.clone();
environment.as_object_mut().unwrap().remove("manager");
runtime["npy_environment"] = environment;
}
runtime["workspace"]["root"] = root.join("work").to_string_lossy().into_owned().into();
atomic_json(&runtime_path, &runtime)?;
if kind == "study" {
let path = effective.join("wf_configs/study.json");
let mut study: serde_json::Value = serde_json::from_reader(std::fs::File::open(&path)?)?;
if let Some(phases) = study["phases"].as_object_mut() {
for phase in phases.values_mut() {
if let Some(tasks) = phase
.get_mut("tasks")
.and_then(serde_json::Value::as_array_mut)
{
for task in tasks {
if let Some(python) = task.get_mut("python") {
let key = crate::config::python_capture_key(python.clone())
.map_err(crate::study::StudyError::from)?;
if let Some(environment) = python_bindings.get(&key) {
python["environment"] = environment.clone();
}
}
}
}
}
}
if let Some(python) = study.pointer_mut("/verification/python") {
let key = crate::config::python_capture_key(python.clone())
.map_err(crate::study::StudyError::from)?;
if let Some(environment) = python_bindings.get(&key) {
python["environment"] = environment.clone();
}
}
atomic_json(&path, &study)?;
}
rewrite_paths(
&effective.join(if kind == "campaign" {
"campaign.json"
} else {
"wf_configs/study.json"
}),
&bindings,
input,
&effective,
)?;
for file in ["wf_configs/parameters.json", "wf_configs/study.json"] {
let path = effective.join(file);
if path.exists() {
rewrite_paths(&path, &bindings, input, &effective)?;
}
}
crate::provenance::capture_tree(
&store,
&effective,
"reproduction/effective-inputs",
None,
&mut artifacts,
)?;
let numerical_path = root.join("reproduction/environment/numerical.json");
atomic_json(&numerical_path, &numerical)?;
crate::provenance::capture_file(
&store,
&numerical_path,
"reproduction/environment/numerical.json",
None,
&mut artifacts,
ArtifactRole::Reproduction,
)?;
let environment = serde_json::json!({"os":std::env::consts::OS,"arch":std::env::consts::ARCH,"runner_sha256":crate::artifact::digest_reader(std::fs::File::open(&runner)?)?.0,"software_bindings":bindings,"seed_algorithm":"scientific-workflow.seed.v1"});
let environment_path = root.join("reproduction/environment/manifest.json");
atomic_json(&environment_path, &environment)?;
crate::provenance::capture_file(
&store,
&environment_path,
"reproduction/environment/manifest.json",
None,
&mut artifacts,
ArtifactRole::Reproduction,
)?;
if kind == "campaign" {
super::campaign::capture_members(
&store,
&root,
&effective,
&settings.storage,
&mut artifacts,
)?;
if crate::workspace::bytes(&root)? > settings.workspace.max_bytes.get() {
return Err(
io::Error::other("campaign capture exceeds its explicit workspace budget").into(),
);
}
}
let science = artifacts
.iter()
.filter(|(key, _)| {
!key.ends_with("runtime.json")
&& (!key.starts_with("reproduction/environment/")
|| *key == "reproduction/environment/numerical.json")
&& !key.starts_with("reproduction/effective-inputs/")
})
.map(|(k, r)| (k.clone(), r.sha256.clone()))
.collect::<std::collections::BTreeMap<_, _>>();
let scientific_identity = crate::artifact::digest_bytes(&serde_json::to_vec(&science)?);
let manifest = RunManifest {
format: "scientific-workflow-run.v1".into(),
run_id: id.clone(),
kind: kind.into(),
scientific_identity,
artifacts,
capture_complete: true,
outcome: Outcome::Starting,
removed: Vec::new(),
};
startup.manifest = manifest.clone();
store.put_json(&format!("{id}/manifest.json"), &manifest, &root, false)?;
crate::registry::index_manifest(&store, &manifest, &root)?;
let mut socket = root.join("engine.sock");
if socket.as_os_str().len() > 100 {
let socket_root =
std::env::temp_dir().join(format!("workflow-sockets-{}", unsafe { libc::geteuid() }));
std::fs::create_dir_all(&socket_root)?;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
let metadata = std::fs::symlink_metadata(&socket_root)?;
if metadata.file_type().is_symlink() || metadata.uid() != unsafe { libc::geteuid() } {
return Err(
io::Error::other("socket directory must be owned by the current user").into(),
);
}
std::fs::set_permissions(&socket_root, std::fs::Permissions::from_mode(0o700))?;
socket = socket_root.join(format!("{id}.sock"));
if socket.as_os_str().len() > 100 {
return Err(io::Error::other("temporary socket directory is too long").into());
}
}
let handle = RunHandle {
run_id: id,
workspace: root.clone(),
socket,
storage: settings.storage,
host_id: crate::workspace::host_id(),
input: input.into(),
};
let mut paths = bindings
.values()
.filter_map(|p| {
if p.is_dir() {
Some(p.join("bin"))
} else {
p.parent().map(Path::to_path_buf)
}
})
.collect::<Vec<_>>();
paths.extend(std::env::split_paths(
&std::env::var_os("PATH").unwrap_or_default(),
));
let captured_path = std::env::join_paths(paths).map_err(io::Error::other)?;
let spec = LaunchSpec {
handle: handle.clone(),
input: effective,
manifest,
max_bytes: settings.workspace.max_bytes.get(),
path: captured_path,
};
atomic_json(&root.join("launch.json"), &spec)?;
atomic_json(&root.join("handle.json"), &handle)?;
store.put_json(
&format!("{}/records/handle.json", handle.run_id),
&handle,
&root,
false,
)?;
drop(lease);
if !capture_only {
spawn_prepared(&handle)?;
}
startup.armed = false;
Ok(handle)
}
pub(super) fn spawn_prepared(handle: &RunHandle) -> Result<(), WorkflowError> {
let root = handle.workspace.clone();
let spec: LaunchSpec = serde_json::from_reader(std::fs::File::open(root.join("launch.json"))?)?;
let numerical =
crate::provenance::read_environment(&root.join("reproduction/environment/numerical.json"))?;
let log = std::fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(root.join("engine.log"))?;
let mut command = Command::new(root.join("reproduction/software/runner"));
command
.env("PATH", spec.path)
.arg("--workflow-engine")
.arg(root.join("launch.json"))
.current_dir(&root)
.env("WORKFLOW_RUN_HANDLE", root.join("handle.json"))
.env("LD_LIBRARY_PATH", root.join("reproduction/libraries"))
.env("PYTHONDONTWRITEBYTECODE", "1")
.stdin(Stdio::null())
.stdout(Stdio::from(log.try_clone()?))
.stderr(Stdio::from(log));
crate::provenance::apply_environment(&mut command, &numerical);
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
unsafe {
command.pre_exec(|| {
if libc::setsid() < 0 {
return Err(io::Error::last_os_error());
}
Ok(())
});
}
}
let mut child = command.spawn()?;
let started = Instant::now();
loop {
if handle.client().is_ok() {
break;
}
if let Some(status) = child.try_wait()? {
return Err(io::Error::other(format!(
"engine failed startup ({status}); inspect {}",
root.join("engine.log").display()
))
.into());
}
if started.elapsed() > Duration::from_secs(60) {
let _ = child.kill();
return Err(
io::Error::new(io::ErrorKind::TimedOut, "engine readiness timed out").into(),
);
}
std::thread::sleep(Duration::from_millis(20));
}
Ok(())
}
pub(super) fn copy_tree(from: &Path, to: &Path) -> io::Result<()> {
for e in std::fs::read_dir(from)? {
let e = e?;
let target = to.join(e.file_name());
if e.file_type()?.is_dir() {
std::fs::create_dir(&target)?;
copy_tree(&e.path(), &target)?;
} else {
crate::workspace::reserve_copy(&target, e.metadata()?.len())?;
std::fs::copy(e.path(), target)?;
}
}
Ok(())
}
pub(super) fn rewrite_paths(
path: &Path,
bindings: &std::collections::BTreeMap<PathBuf, PathBuf>,
original: &Path,
effective: &Path,
) -> io::Result<()> {
fn visit(
value: &mut serde_json::Value,
bindings: &std::collections::BTreeMap<PathBuf, PathBuf>,
original: &Path,
effective: &Path,
) {
match value {
serde_json::Value::String(s) => {
let path = Path::new(s);
if let Some((source, bound)) = bindings
.iter()
.filter(|(source, _)| path.starts_with(source))
.max_by_key(|(source, _)| source.components().count())
{
let relative = path.strip_prefix(source).unwrap();
*s = if relative.as_os_str().is_empty() {
bound.clone()
} else {
bound.join(relative)
}
.to_string_lossy()
.into_owned();
} else if let Ok(relative) = path.strip_prefix(original) {
*s = effective.join(relative).to_string_lossy().into_owned();
}
}
serde_json::Value::Object(o) => {
for v in o.values_mut() {
visit(v, bindings, original, effective);
}
}
serde_json::Value::Array(a) => {
for v in a {
visit(v, bindings, original, effective);
}
}
_ => {}
}
}
let mut value = serde_json::from_slice(&std::fs::read(path)?).map_err(io::Error::other)?;
visit(&mut value, bindings, original, effective);
atomic_json(path, &value)
}