agentmux_srv/drone/executor/blocks/
run.rs1use serde_json::{json, Value};
32
33use crate::backend::container::image::{resolve_container_image, DEFAULT_AGENT_IMAGE};
34use crate::backend::container::oneshot::{OneShot, OneShotOutcome};
35use crate::drone::data_flow::ExecutionScope;
36use crate::drone::types::FlowNode;
37
38pub const MAX_TIMEOUT_SECONDS: u64 = 3_600;
40const ERROR_TAIL_CHARS: usize = 300;
42const NOT_YET: [&str; 6] = ["mounts", "hosts", "network", "vault", "secrets", "stdin"];
44
45#[derive(Debug, PartialEq)]
47pub(crate) struct RunSpec {
48 pub image: Option<String>,
49 pub command: Vec<String>,
50 pub env: Vec<(String, String)>,
51 pub cwd: Option<String>,
52 pub ok_exit_codes: Vec<i64>,
53}
54
55pub(crate) fn parse(node: &FlowNode) -> Result<RunSpec, String> {
57 let data = &node.data;
58 for key in NOT_YET {
59 if data.get(key).is_some_and(|v| !v.is_null()) {
60 return Err(format!("run block: `{key}` is not supported yet: the command runs with no network, no mounts and no secrets"));
61 }
62 }
63 match data.get("where").and_then(Value::as_str).map(str::trim) {
64 None | Some("") | Some("container") => {}
65 Some("host") => return Err("run block: `where: host` needs a named allowance that this build can't give yet; use `where: container`".to_string()),
66 Some(other) => return Err(format!("run block: `where` is `container` or `host`, not `{other}`")),
67 }
68 let command: Vec<String> = data
69 .get("command")
70 .and_then(Value::as_array)
71 .ok_or("run block: `command` must be a list, the program and then its arguments")?
72 .iter()
73 .map(|a| a.as_str().map(str::to_string).ok_or("run block: every item of `command` must be text"))
74 .collect::<Result<_, _>>()?;
75 if command.first().map_or(true, |program| program.trim().is_empty()) {
76 return Err("run block: `command` needs a program as its first item".to_string());
77 }
78 let env = match data.get("env") {
79 None | Some(Value::Null) => Vec::new(),
80 Some(Value::Object(map)) => map
81 .iter()
82 .map(|(k, v)| {
83 let valid = !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') && !k.starts_with(|c: char| c.is_ascii_digit());
84 match (valid, v.as_str()) {
85 (true, Some(text)) => Ok((k.clone(), text.to_string())),
86 (false, _) => Err(format!("run block: `{k}` is not a name an environment variable can have")),
87 (_, None) => Err(format!("run block: `env.{k}` must be text")),
88 }
89 })
90 .collect::<Result<_, _>>()?,
91 Some(_) => return Err("run block: `env` must be an object of names and text".to_string()),
92 };
93 let cwd = match data.get("cwd") {
94 None | Some(Value::Null) => None,
95 Some(Value::String(s)) if s.trim().is_empty() => None,
96 Some(Value::String(s)) => Some(s.trim().to_string()),
97 Some(_) => return Err("run block: `cwd` must be text".to_string()),
98 };
99 let image = match data.get("image") {
100 None | Some(Value::Null) => None,
101 Some(Value::String(s)) if s.trim().is_empty() => None,
102 Some(Value::String(s)) if s.contains("{{") => return Err("run block: `image` must be written in the graph, not a {{reference}}".to_string()),
103 Some(Value::String(s)) => Some(s.trim().to_string()),
104 Some(_) => return Err("run block: `image` must be text".to_string()),
105 };
106 let ok_exit_codes = match data.get("ok_exit_codes") {
107 None | Some(Value::Null) => vec![0],
108 Some(Value::Array(items)) if !items.is_empty() => {
109 items.iter().map(|c| c.as_i64().ok_or("run block: `ok_exit_codes` must be a list of whole numbers")).collect::<Result<_, _>>()?
110 }
111 Some(_) => return Err("run block: `ok_exit_codes` must be a list of whole numbers".to_string()),
112 };
113 if let Some(secs) = data.get("timeout_seconds").and_then(Value::as_u64) {
114 if secs > MAX_TIMEOUT_SECONDS {
115 return Err(format!("run block: `timeout_seconds` is at most {MAX_TIMEOUT_SECONDS} (60 minutes)"));
116 }
117 }
118 Ok(RunSpec { image, command, env, cwd, ok_exit_codes })
119}
120
121pub fn check(node: &FlowNode) -> Result<(), String> {
123 parse(node).map(|_| ())
124}
125
126pub(crate) fn compose(node: &FlowNode, scope: &ExecutionScope) -> Result<(OneShot, Vec<i64>), String> {
128 let spec = parse(node)?;
129 let clean = |what: String, template: &str| -> Result<String, String> {
130 let (tainted, derived) = scope.bits_of(template);
131 if tainted || derived {
132 let why = if tainted { "text from outside the drone" } else { "a value worked out from text from outside the drone" };
133 return Err(format!("run block: {what} reads {why}; a command line is never built from outside text"));
134 }
135 Ok(scope.resolve(template))
136 };
137 let mut argv = Vec::with_capacity(spec.command.len());
138 for (i, arg) in spec.command.iter().enumerate() {
139 argv.push(clean(format!("`command[{i}]`"), arg)?);
140 }
141 if argv[0].trim().is_empty() {
142 return Err("run block: the program is empty once its references are filled in".to_string());
143 }
144 let mut env = Vec::with_capacity(spec.env.len());
145 for (name, value) in &spec.env {
146 env.push((name.clone(), clean(format!("`env.{name}`"), value)?));
147 }
148 let cwd = spec.cwd.as_deref().map(|c| clean("`cwd`".to_string(), c)).transpose()?;
149 let image = spec.image.unwrap_or_else(|| resolve_container_image(DEFAULT_AGENT_IMAGE));
150 Ok((OneShot { image, argv, env, cwd }, spec.ok_exit_codes))
151}
152
153pub async fn run(node: &FlowNode, scope: &ExecutionScope) -> Result<Value, String> {
154 let (one, ok_codes) = compose(node, scope)?;
155 let state = crate::drone::host::state()?;
156 let manager = state.container_manager.get_or_explain().await.map_err(|e| format!("run block: {e}"))?;
157 let outcome = manager.run_oneshot(&one).await.map_err(|e| format!("run block: {e}"))?;
158 outcome_of(&outcome, &ok_codes)
159}
160
161pub(crate) fn outcome_of(done: &OneShotOutcome, ok_codes: &[i64]) -> Result<Value, String> {
163 if !ok_codes.contains(&done.exit_code) {
164 let tail = tail_line(&done.stderr);
165 return Err(if tail.is_empty() { format!("run block: the command exited with code {}", done.exit_code) } else { format!("run block: the command exited with code {}: {tail}", done.exit_code) });
166 }
167 Ok(json!({
168 "exit_code": done.exit_code,
169 "stdout": done.stdout,
170 "stderr": done.stderr,
171 "duration_ms": done.duration_ms,
172 "truncated": done.truncated,
173 }))
174}
175
176fn tail_line(text: &str) -> String {
178 let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
179 let count = flat.chars().count();
180 if count <= ERROR_TAIL_CHARS {
181 return flat;
182 }
183 let tail: String = flat.chars().skip(count - ERROR_TAIL_CHARS).collect();
184 format!("…{tail}")
185}
186
187#[cfg(test)]
188#[path = "run_tests.rs"]
189mod tests;